Adaptiven A1-Kurs und statistisches Aussprachetraining integrieren
Direkte DeepSeek- und Mistral-Anbindung mit versionierten Aktionsprofilen, Budgetreservierung, Tokenabrechnung und administrativen Qualitätsprüfungen ersetzen die Flowise-Abhängigkeit im regulären Betrieb. 840 geprüfte A1-Aufgaben mit geschützter Testauswertung und konkreten offenen Arbeitsaufträgen ergänzen den Kurs. Inhalts- und Sprachbewertung bleiben von Azure-Aussprachewerten getrennt; historische Aufgaben und Antworten bleiben erhalten. Echte Wort- und Phonemmessungen werden mit Herkunft, Aktualität und Nachweisdichte gebündelt. Go bestimmt Trainingsziele und Wiederholungen, das Modell formuliert dazu passende Nachsprechübungen. Profilansicht und Auswahlgründe werden angezeigt. Validierung: Go-Race-Tests mit lokaler PostgreSQL-Integration, go vet, Web-Build, Audit aller 840 Aufgaben und drei Browser-Smokes mit lokalen Modell-/Speech-Fixtures bestanden. Keine Produktionsänderungen oder Live-Aufrufe.
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
import { request, requestBlob } from './client';
|
||||
import type { LearnerProfile, WordScore } from './types';
|
||||
|
||||
type LanguageProfile = { code: string; display_name: string; azure_locale: string; supports_pronunciation_assessment: boolean };
|
||||
type PronunciationResult = { recognized_text: string; overall_score: number; accuracy_score: number; word_scores: WordScore[]; provider: string };
|
||||
|
||||
export const courseSkills = ['grammar', 'vocabulary', 'listening', 'reading', 'speaking', 'writing'] as const;
|
||||
export type CourseSkill = typeof courseSkills[number];
|
||||
export const courseSkillNames: Record<CourseSkill, string> = { grammar: 'Grammatik', vocabulary: 'Wortschatz', listening: 'Hören', reading: 'Lesen', speaking: 'Sprechen', writing: 'Schreiben' };
|
||||
export type AdaptiveModule = { id: string; key: string; title: string; description: string; target_language: string; order: number; goals: string[] };
|
||||
export type AdaptiveTask = {
|
||||
schema_version: 2; id: string; module_id: string; target_language: string; skill: CourseSkill;
|
||||
kind: 'choice' | 'short_text' | 'free_text' | 'repeat_sentence' | 'free_speech'; prompt: string;
|
||||
options?: { id: string; label: string }[]; passage?: string; reference_text?: string; audio_text?: string;
|
||||
source: 'seed' | 'flowise' | 'ai' | 'curated'; exam_id?: string; review?: boolean;
|
||||
answer_key?: { correct_option_id?: string; reference_answer?: string; explanation: string; rubric: string[] };
|
||||
};
|
||||
export type AdaptiveAttempt = {
|
||||
id: string; task_id: string; answer: string; status: 'pending' | 'graded' | 'failed' | 'ungraded'; demo: boolean; exam_id?: string;
|
||||
evaluation?: { score: number; verdict: string; feedback: string; issues: string[] };
|
||||
speech?: PronunciationResult;
|
||||
};
|
||||
export type CourseAnalysis = {
|
||||
summary: string; facts_version: number; recommended_module_id: string;
|
||||
modules: { module_id: string; strengths: string[]; weaknesses: string[]; recommendation: string; reason: string; ready_for_completion: boolean }[];
|
||||
};
|
||||
export type CourseCatalog = {
|
||||
task_mode?: string; grading_available?: boolean; bank?: {module_id:string;skill:CourseSkill;total:number;unseen:number}[];
|
||||
profile: LearnerProfile; modules: AdaptiveModule[];
|
||||
progress: { module_id: string; skill: CourseSkill; attempts: number; distinct_tasks: number; average_score: number }[];
|
||||
analysis_job?: CourseJob; analysis: CourseAnalysis | null; facts_version: number; enabled_languages: string[]; languages: LanguageProfile[];
|
||||
exams: { id: string; target_language: string; status: string }[];
|
||||
};
|
||||
export type CourseJob = { id: string; kind: string; status: string; stage: string; task_id?: string; subject_id?: string; error?: string; source?: string; review?: boolean };
|
||||
export type AdaptiveExam = { id: string; status: string; target_language: string; tasks: AdaptiveTask[]; attempts: AdaptiveAttempt[]; scores?: Record<CourseSkill, number>; score?: number; summary?: string; summary_status?: string; summary_job_id?: string; preparation_job_id?: string };
|
||||
export function courseRequestID() { return Array.from(crypto.getRandomValues(new Uint8Array(16)), (b) => b.toString(16).padStart(2, '0')).join(''); }
|
||||
export const getCourseCatalog = () => request<CourseCatalog>('/course/catalog');
|
||||
export const getCourseHistory = (module: string, offset = 0) => request<{ tasks: AdaptiveTask[]; has_more: boolean }>(`/course/modules/${encodeURIComponent(module)}/tasks?offset=${offset}`);
|
||||
export const getAdaptiveTask = (id: string) => request<{ task: AdaptiveTask; attempt: AdaptiveAttempt | null }>(`/course/tasks/${encodeURIComponent(id)}`);
|
||||
export const createCourseTask = (module: string, skill: string, requestId: string) => request<CourseJob>(`/course/modules/${encodeURIComponent(module)}/tasks/next`, { method: 'POST', body: JSON.stringify({ skill, request_id: requestId }) });
|
||||
export const getCourseJob = (id: string) => request<CourseJob>(`/course/jobs/${encodeURIComponent(id)}`);
|
||||
export const retryCourseJob = (id: string) => request<CourseJob>(`/course/jobs/${encodeURIComponent(id)}/retry`, { method: 'POST' });
|
||||
export const getCourseAttempt = (id: string) => request<AdaptiveAttempt>(`/course/attempts/${encodeURIComponent(id)}`);
|
||||
export const retryCourseAttempt = (id: string) => request<CourseJob>(`/course/attempts/${encodeURIComponent(id)}/retry`, { method: 'POST' });
|
||||
export const answerCourseTask = (id: string, answer: string, requestId: string) => request<{ attempt: AdaptiveAttempt; job?: CourseJob }>(`/course/tasks/${encodeURIComponent(id)}/attempts`, { method: 'POST', body: JSON.stringify({ answer, request_id: requestId }) });
|
||||
export function answerCourseAudio(id: string, audio: Blob, requestId: string) {
|
||||
const body = new FormData(); body.append('audio', audio, 'recording.wav'); body.append('request_id', requestId);
|
||||
return request<{ attempt: AdaptiveAttempt; job?: CourseJob }>(`/course/tasks/${encodeURIComponent(id)}/audio-attempts`, { method: 'POST', body });
|
||||
}
|
||||
export const getAdaptiveAudio = (id: string) => requestBlob(`/course/tasks/${encodeURIComponent(id)}/audio`);
|
||||
export const createCourseExam = (requestId: string) => request<{ exam: AdaptiveExam; job: CourseJob }>('/course/exams', { method: 'POST', body: JSON.stringify({ request_id: requestId }) });
|
||||
export const getCourseExam = (id: string) => request<AdaptiveExam>(`/course/exams/${encodeURIComponent(id)}`);
|
||||
@@ -0,0 +1,20 @@
|
||||
import { request } from './client';
|
||||
export const aiActions: Record<string,string> = {
|
||||
analyze_course_progress:'Lernanalyse', plan_course_task:'Aufgabenplanung', author_course_task:'Aufgabenautor', review_course_task:'Aufgabenprüfung',
|
||||
author_course_exam:'Testautor · 12 Aufgaben', review_course_exam:'Testprüfung · 12 Aufgaben', evaluate_course_attempt:'Antwortbewertung', summarize_course_exam:'Testzusammenfassung', next_exercise:'Aussprachegenerierung'
|
||||
};
|
||||
export type AIProfile={action:string;version:number;enabled:boolean;provider:string;model:string;temperature:number|null;reasoning_effort:string;max_tokens:number;context_tokens:number;timeout_seconds:number;json_schema:boolean;pricing_set:boolean;input_microusd_per_million:number;cached_input_microusd_per_million:number;output_microusd_per_million:number};
|
||||
export type AIBudget={monthly_limit_microusd:number;daily_limit_microusd:number;month_committed_microusd:number;day_committed_microusd:number;open_reservations_microusd:number;warning:boolean;currency:string};
|
||||
export type AISettings={profiles:Record<string,AIProfile>;budget:AIBudget;providers:Record<string,boolean>;prompt_version:string;prompts:Record<string,string>;schemas:Record<string,string>};
|
||||
export type AICall={id:string;operation_id:string;user_id:string;action:string;provider:string;model:string;profile:AIProfile;prompt_version:string;attempt:number;status:string;reserved_microusd:number;cost_microusd?:number;usage?:{input_tokens:number;output_tokens:number;cached_tokens?:number;reasoning_tokens?:number};input?:string;output?:string;error?:string;duration_ms:number;test:boolean;created_at:string};
|
||||
export type AIUsage={calls:AICall[];total:number;input_tokens:number;output_tokens:number;unknown_usage_calls:number;estimated_cost_microusd:number;reserved_microusd:number};
|
||||
export const getAISettings=()=>request<AISettings>('/admin/ai/settings');
|
||||
export const saveAIProfile=(p:AIProfile)=>request<AIProfile>(`/admin/ai/profiles/${p.action}`,{method:'PUT',body:JSON.stringify(p)});
|
||||
export const saveAIBudget=(monthly:number,daily:number)=>request<AIBudget>('/admin/ai/budget',{method:'PUT',body:JSON.stringify({monthly_limit_microusd:monthly,daily_limit_microusd:daily})});
|
||||
export const getAIModels=(provider:string)=>request<{data:{id:string;name?:string;context_window?:number;max_context_length?:number;max_output_tokens?:number}[]}>(`/admin/ai/providers/${provider}/models`);
|
||||
export const getAIUsage=(query:URLSearchParams)=>request<AIUsage>(`/admin/ai/usage?${query}`);
|
||||
export const getAICall=(id:string)=>request<AICall>(`/admin/ai/calls/${id}`);
|
||||
export const resolveAICall=(id:string,cost:number,reason:string)=>request(`/admin/ai/calls/${id}/resolve`,{method:'POST',body:JSON.stringify({cost_microusd:cost,reason})});
|
||||
export const testAI=(action:string,input:unknown,request_id:string)=>request<{ok:boolean;error?:string;output?:unknown;operation_id:string;profile:AIProfile;prompt_version:string}>('/admin/ai/test',{method:'POST',body:JSON.stringify({action,input,request_id})});
|
||||
|
||||
export const testAIQuality=(request_id:string,suite:'grammar'|'writing'='grammar')=>request<unknown>('/admin/ai/quality',{method:'POST',body:JSON.stringify({request_id,suite})});
|
||||
@@ -0,0 +1,30 @@
|
||||
import { request, requestBlob } from './client';
|
||||
import type { CourseAttemptResult, CourseModule, CourseModuleDetail, CourseTask, CoursePracticeResult } from './types';
|
||||
|
||||
export function fetchCourseModules() {
|
||||
return request<{ modules: CourseModule[] }>('/course/modules');
|
||||
}
|
||||
|
||||
export function fetchCourseModule(id: string) {
|
||||
return request<CourseModuleDetail>(`/course/modules/${encodeURIComponent(id)}`);
|
||||
}
|
||||
|
||||
export function submitCourseAnswer(taskId: string, answer: string) {
|
||||
return request<CourseAttemptResult>(`/course/tasks/${encodeURIComponent(taskId)}/attempts`, {
|
||||
method: 'POST', body: JSON.stringify({ answer })
|
||||
});
|
||||
}
|
||||
|
||||
export function fetchCourseAudio(taskId: string) {
|
||||
return requestBlob(`/course/tasks/${encodeURIComponent(taskId)}/audio`);
|
||||
}
|
||||
|
||||
export function fetchCoursePractice(moduleId: string) {
|
||||
return request<{ tasks: CourseTask[] }>(`/course/modules/${encodeURIComponent(moduleId)}/practice`);
|
||||
}
|
||||
|
||||
export function nextCoursePractice(moduleId: string, requestId: string) {
|
||||
return request<CoursePracticeResult>(`/course/modules/${encodeURIComponent(moduleId)}/practice/next`, {
|
||||
method: 'POST', body: JSON.stringify({ request_id: requestId })
|
||||
});
|
||||
}
|
||||
@@ -20,7 +20,7 @@ export type DebugStatus = {
|
||||
checks: {
|
||||
db: DebugDB;
|
||||
azure: DebugCheck;
|
||||
flowise: DebugCheck;
|
||||
ai: DebugCheck;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -40,8 +40,8 @@ export function fetchDebugDB() {
|
||||
return request<{ request_id: string; db: DebugDB }>('/debug/db');
|
||||
}
|
||||
|
||||
export function fetchDebugFlowise() {
|
||||
return request<{ request_id: string; flowise: DebugCheck }>('/debug/flowise');
|
||||
export function fetchDebugAI() {
|
||||
return request<{ request_id: string; ai: DebugCheck }>('/debug/ai');
|
||||
}
|
||||
|
||||
export function fetchDebugAzure() {
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { request } from './client';
|
||||
export type PronunciationTarget = {
|
||||
key: string; kind: 'word'|'phoneme'|'omission'; locale: string; alphabet: string; symbol: string;
|
||||
mean: number; weak_rate: number; observations: number; samples: number; recordings: number; tasks: number; words: number;
|
||||
state: string; trend: string; last_seen: string; next_review?: string; review_due: boolean;
|
||||
examples: {word:string;mean:number;samples:number}[];
|
||||
};
|
||||
export type PronunciationProfile = {
|
||||
algorithm:string;language:string;as_of:string;window_days:number;confirmed_recordings:number;unverified_history:number;targets:PronunciationTarget[];
|
||||
};
|
||||
export const fetchPronunciationProfile=()=>request<PronunciationProfile>('/pronunciation/profile');
|
||||
@@ -47,6 +47,8 @@ export type Lesson = {
|
||||
};
|
||||
|
||||
export type Exercise = {
|
||||
training_reason?: string;
|
||||
training_category?: string;
|
||||
id: string;
|
||||
lesson_id: string;
|
||||
target_language: string;
|
||||
@@ -55,7 +57,7 @@ export type Exercise = {
|
||||
prompt_text: string;
|
||||
target_text: string;
|
||||
difficulty: number;
|
||||
source?: 'seed' | 'flowise' | 'fallback' | string;
|
||||
source?: 'seed' | 'flowise' | 'ai' | 'fallback' | string;
|
||||
};
|
||||
|
||||
export type WordScore = {
|
||||
@@ -131,3 +133,34 @@ export type AttemptResponse = {
|
||||
teacher: TeacherResponse;
|
||||
provider: string;
|
||||
};
|
||||
|
||||
export type CourseModule = {
|
||||
id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
target_language: string;
|
||||
cefr_level: string;
|
||||
version: number;
|
||||
task_count: number;
|
||||
attempted_count: number;
|
||||
correct_count: number;
|
||||
};
|
||||
|
||||
export type CourseTask = {
|
||||
source?: 'flowise' | 'seed' | 'ai' | 'curated';
|
||||
id: string;
|
||||
module_id: string;
|
||||
skill: 'vocabulary' | 'listening' | 'reading' | 'grammar' | 'writing' | 'pronunciation';
|
||||
kind: 'choice' | 'short_text' | 'pronunciation';
|
||||
prompt: string;
|
||||
passage?: string;
|
||||
options?: string[];
|
||||
pronunciation_exercise?: Exercise;
|
||||
attempted: boolean;
|
||||
correct: boolean;
|
||||
};
|
||||
|
||||
export type CourseModuleDetail = { module: CourseModule; tasks: CourseTask[] };
|
||||
export type CourseAttemptResult = { id: string; task_id: string; correct: boolean; solution: string; explanation: string; transcript?: string };
|
||||
|
||||
export type CoursePracticeResult = { task: CourseTask; source: 'flowise' | 'seed' | 'ai' | 'curated' };
|
||||
|
||||
@@ -11,6 +11,7 @@ import { RegisterPage } from '../pages/RegisterPage';
|
||||
import { PracticePage } from '../pages/PracticePage';
|
||||
import { ProgressPage } from '../pages/ProgressPage';
|
||||
import { ConversationPage } from '../pages/ConversationPage';
|
||||
import { CoursePage } from '../pages/CoursePage';
|
||||
import { DebugPage } from '../pages/DebugPage';
|
||||
import { useHashRoute } from './useHashRoute';
|
||||
|
||||
@@ -124,7 +125,7 @@ export function App() {
|
||||
<div className="brand-mark">SL</div>
|
||||
<div>
|
||||
<strong>Speech Learning</strong>
|
||||
<span>A1 English</span>
|
||||
<span>A1 Sprachlernen</span>
|
||||
</div>
|
||||
</div>
|
||||
<nav className="nav-list">
|
||||
@@ -134,6 +135,9 @@ export function App() {
|
||||
<button className={route === 'practice' ? 'active' : ''} onClick={() => setRoute('practice')}>
|
||||
<Mic size={18} /> Aussprache
|
||||
</button>
|
||||
<button className={route === 'course' ? 'active' : ''} onClick={() => setRoute('course')}>
|
||||
<BookOpen size={18} /> A1-Kurs
|
||||
</button>
|
||||
<button className={route === 'conversation' ? 'active' : ''} onClick={() => setRoute('conversation')}>
|
||||
<MessageCircle size={18} /> Dialog
|
||||
</button>
|
||||
@@ -160,6 +164,7 @@ export function App() {
|
||||
<main className="main-view">
|
||||
{route === 'dashboard' && <DashboardPage onLoaded={(lesson, exercise) => setPracticeSelection({ lesson, exercise })} onPractice={openDashboardExercise} />}
|
||||
{route === 'practice' && <PracticePage initialSelection={practiceSelection} />}
|
||||
{route === 'course' && <CoursePage />}
|
||||
{route === 'conversation' && <ConversationPage />}
|
||||
{route === 'progress' && <ProgressPage />}
|
||||
{route === 'admin' && (user.role === 'admin' ? <AdminPage /> : <p className="form-error">Kein Zugriff auf den Adminbereich.</p>)}
|
||||
|
||||
@@ -321,6 +321,33 @@ input:focus {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.course-progress {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.course-progress p { margin: 0; }
|
||||
.course-progress progress { width: 100%; accent-color: #0e5f47; }
|
||||
.course-additional { display: flex; align-items: center; justify-content: space-between; gap: 18px; flex-wrap: wrap; }
|
||||
.course-additional h2 { margin: 0 0 6px; font-size: 1.1rem; }
|
||||
.course-additional p { margin: 0; }
|
||||
.course-practice-status { flex-basis: 100%; }
|
||||
.course-exercise { scroll-margin-top: 24px; }
|
||||
.course-layout { display: grid; grid-template-columns: minmax(210px, 270px) minmax(0, 1fr); gap: 18px; align-items: start; }
|
||||
.course-task-list, .course-exercise, .course-skill-group, .course-options, .course-pronunciation { display: grid; gap: 14px; }
|
||||
.course-skill-group { gap: 7px; }
|
||||
.course-skill-group h2 { font-size: 1rem; margin: 0; display: grid; gap: 3px; }
|
||||
.course-skill-group small { color: #66736c; }
|
||||
.course-task { width: 100%; display: flex; justify-content: space-between; background: #eef1ef; color: #17201b; padding: 10px 12px; border-radius: 8px; text-align: left; }
|
||||
.course-task.active { background: #d4e9dc; outline: 2px solid #0e5f47; }
|
||||
.course-exercise h2 { margin: 0; }
|
||||
.course-passage { background: #eef1ef; padding: 16px; border-radius: 8px; line-height: 1.6; }
|
||||
.course-option { display: flex; align-items: center; gap: 10px; border: 1px solid #d9dfdc; border-radius: 8px; padding: 10px; cursor: pointer; }
|
||||
.course-option input { width: auto; }
|
||||
.course-feedback { padding: 15px; background: #fff3c9; border-radius: 8px; }
|
||||
.course-feedback.correct { background: #e5f4ec; }
|
||||
.course-feedback p { margin-bottom: 0; }
|
||||
|
||||
.result-grid {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
|
||||
@@ -634,6 +661,7 @@ input:focus {
|
||||
}
|
||||
|
||||
@media (max-width: 760px) {
|
||||
.course-layout { grid-template-columns: 1fr; }
|
||||
.app-shell {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
@@ -681,3 +709,23 @@ input:focus {
|
||||
justify-content: space-between;
|
||||
}
|
||||
}
|
||||
|
||||
/* Curriculum and tasks share renderers across target languages. */
|
||||
.course-module-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); gap: 12px; }
|
||||
.course-module-card { display: grid; gap: 10px; text-align: left; color: inherit; cursor: pointer; }
|
||||
.course-module-card.selected { outline: 2px solid #0e5f47; background: #e5f4ec; }
|
||||
.course-module-card strong { font-size: 1.1rem; }
|
||||
.course-area-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 8px; }
|
||||
.course-progress-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 12px; }
|
||||
.course-progress-grid p { color: #66736c; margin: 6px 0 0; font-size: .9rem; }
|
||||
.course-analysis h2 { margin-top: 0; }
|
||||
.course-exercise textarea { width: 100%; min-height: 80px; padding: 12px; border: 1px solid #c9d3cd; border-radius: 8px; font: inherit; }
|
||||
|
||||
.ai-form-grid { display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:1rem; }
|
||||
.ai-admin label { display:flex;flex-direction:column;gap:.35rem; }
|
||||
.ai-admin label:has(input[type="checkbox"]) {flex-direction:row;align-items:center;}
|
||||
.ai-admin pre {white-space:pre-wrap;overflow-wrap:anywhere;max-height:28rem;overflow:auto;background:var(--bg,#f5f6f8);padding:1rem;border-radius:.5rem;}
|
||||
.ai-admin textarea {width:100%;font-family:monospace;}
|
||||
|
||||
.pronunciation-target { border-bottom: 1px solid var(--border, #dce2e8); padding-bottom: 1rem; }
|
||||
.pronunciation-target p { margin: .35rem 0; }
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { aiActions, getAISettings, saveAIProfile, saveAIBudget, getAIModels, getAIUsage, getAICall, resolveAICall, testAI, testAIQuality, type AISettings, type AIProfile, type AIUsage, type AICall } from '../api/ai';
|
||||
import { courseRequestID } from '../api/adaptive';
|
||||
const dollars=(micro:number)=>new Intl.NumberFormat('de-DE',{style:'currency',currency:'USD',minimumFractionDigits:4,maximumFractionDigits:6}).format(micro/1000000);
|
||||
const micro=(value:string)=>Math.round(Number(value||0)*1000000);
|
||||
export function AIAdmin(){
|
||||
const [settings,setSettings]=useState<AISettings|null>(null),[profile,setProfile]=useState<AIProfile|null>(null),[action,setAction]=useState('evaluate_course_attempt');
|
||||
const [error,setError]=useState(''),[notice,setNotice]=useState(''),[busy,setBusy]=useState(false);
|
||||
const [month,setMonth]=useState(''),[day,setDay]=useState(''),[models,setModels]=useState<{id:string}[]>([]);
|
||||
const [usage,setUsage]=useState<AIUsage|null>(null),[filters,setFilters]=useState({from:'',to:'',provider:'',model:'',user:'',action:''}),[offset,setOffset]=useState(0);
|
||||
const [detail,setDetail]=useState<AICall|null>(null),[input,setInput]=useState(''),[testResult,setTestResult]=useState<unknown>(null),[resolveCost,setResolveCost]=useState(''),[reason,setReason]=useState('');
|
||||
const detailPanel=useRef<HTMLDivElement>(null),detailTrigger=useRef<HTMLButtonElement|null>(null);
|
||||
const [detailLoading,setDetailLoading]=useState(false),[detailError,setDetailError]=useState('');
|
||||
useEffect(()=>{if(detail||detailLoading||detailError){detailPanel.current?.focus({preventScroll:true});detailPanel.current?.scrollIntoView({block:'start',behavior:'smooth'});}},[detail,detailLoading,detailError]);
|
||||
function closeDetail(){setDetail(null);setDetailError('');detailTrigger.current?.focus();}
|
||||
async function openDetail(id:string,trigger:HTMLButtonElement){if(busy)return;detailTrigger.current=trigger;setDetail(null);setDetailError('');setDetailLoading(true);await run(async()=>{try{setDetail(await getAICall(id));setResolveCost('');setReason('')}catch(e){setDetailError(e instanceof Error?e.message:'Aufrufdetails konnten nicht geladen werden.')}finally{setDetailLoading(false)}});}
|
||||
const fail=(e:unknown)=>setError(e instanceof Error?e.message:'KI-Verwaltung nicht verfügbar');
|
||||
async function refresh(){const s=await getAISettings();setSettings(s);setMonth(String(s.budget.monthly_limit_microusd/1000000));setDay(String(s.budget.daily_limit_microusd/1000000));return s;}
|
||||
async function refreshUsage(){const q=new URLSearchParams({offset:String(offset)});for(const [k,v]of Object.entries(filters)){if(v)q.set(k,k==='from'||k==='to'?new Date(v).toISOString():v);}setUsage(await getAIUsage(q));}
|
||||
useEffect(()=>{let valid=true;getAISettings().then(s=>{if(valid){setSettings(s);setMonth(String(s.budget.monthly_limit_microusd/1000000));setDay(String(s.budget.daily_limit_microusd/1000000));}}).catch(e=>{if(valid)fail(e)});return()=>{valid=false}},[]);
|
||||
useEffect(()=>{if(settings)setProfile(settings.profiles[action]);setModels([]);setTestResult(null)},[settings?.profiles[action]?.version,action]);
|
||||
useEffect(()=>{let valid=true;const q=new URLSearchParams({offset:String(offset)});for(const [k,v]of Object.entries(filters)){if(v)q.set(k,k==='from'||k==='to'?new Date(v).toISOString():v);}getAIUsage(q).then(u=>{if(valid)setUsage(u)}).catch(e=>{if(valid)fail(e)});return()=>{valid=false}},[filters,offset]);
|
||||
async function run(fn:()=>Promise<void>){if(busy)return;setBusy(true);setError('');setNotice('');try{await fn()}catch(e){fail(e)}finally{setBusy(false)}}
|
||||
function field<K extends keyof AIProfile>(key:K,value:AIProfile[K]){setProfile(p=>p?{...p,[key]:value}:p)}
|
||||
return <section className="view-stack ai-admin" aria-label="KI-Verwaltung">
|
||||
<header><h2>KI-Einstellungen und Verbrauch</h2><p>Direkte Modellaufrufe aus Go. Beträge sind Schätzungen in USD; verbindlich ist die Anbieterrechnung. Tages- und Monatsgrenzen gelten in UTC.</p></header>
|
||||
{error&&<p className="form-error" role="alert">{error}</p>}{notice&&<p role="status">{notice}</p>}
|
||||
{!settings?<p>KI-Einstellungen werden geladen…</p>:<>
|
||||
<div className="panel view-stack"><h3>Budget</h3><p>API-Zugänge: DeepSeek {settings.providers.deepseek?'konfiguriert':'nicht konfiguriert'} · Mistral {settings.providers.mistral?'konfiguriert':'nicht konfiguriert'}</p>
|
||||
<p>Monat gebunden: {dollars(settings.budget.month_committed_microusd)} · Tag gebunden: {dollars(settings.budget.day_committed_microusd)} · Offene Reservierungen: {dollars(settings.budget.open_reservations_microusd)}</p>
|
||||
{settings.budget.warning&&<p role="status">Mindestens 80 % eines Budgets sind belegt.</p>}
|
||||
{settings.budget.monthly_limit_microusd===0&&<p>KI-Aufrufe sind gesperrt, bis ein positives Monatsbudget eingerichtet ist.</p>}
|
||||
<div className="ai-form-grid"><label>Monatslimit in USD<input type="number" min="0" step="0.01" value={month} onChange={e=>setMonth(e.target.value)}/></label><label>Tageslimit in USD · 0 = kein Tageslimit<input type="number" min="0" step="0.01" value={day} onChange={e=>setDay(e.target.value)}/></label></div>
|
||||
<button type="button" disabled={busy} onClick={()=>void run(async()=>{await saveAIBudget(micro(month),micro(day));await refresh();setNotice('Budget gespeichert.');})}>Budget speichern</button>
|
||||
<p className="muted">Vor jedem Aufruf wird eine konservative Obergrenze reserviert. Unbekannter Verbrauch bleibt gebunden, bis du ihn mit der Anbieterrechnung abgleichst. Eine neue Aufgabe kann mehrere Aufrufe benötigen.</p></div>
|
||||
<div className="panel view-stack"><h3>Modellprofile</h3><label>Arbeitsschritt<select value={action} disabled={busy} onChange={e=>setAction(e.target.value)}>{Object.entries(aiActions).map(([id,label])=><option key={id} value={id}>{label}</option>)}</select></label>
|
||||
{profile&&<><p className="muted">Version {profile.version}. Änderungen gelten für neue Aufträge; laufende Aufträge behalten ihre Einstellungen.</p>
|
||||
<div className="ai-form-grid"><label>Anbieter<select value={profile.provider} disabled={busy} onChange={e=>{field('provider',e.target.value);field('json_schema',false);field('reasoning_effort','');setModels([])}}><option value="mistral">Mistral</option><option value="deepseek">DeepSeek</option></select></label>
|
||||
<label>Modell-ID<input list="ai-models" value={profile.model} onChange={e=>{field('model',e.target.value);field('reasoning_effort','')}}/><datalist id="ai-models">{models.map(m=><option key={m.id} value={m.id}/>)}</datalist></label>
|
||||
<label>Maximale Ausgabetokens<input type="number" min="128" max="2097152" value={profile.max_tokens} onChange={e=>field('max_tokens',Number(e.target.value))}/></label>
|
||||
<label>Kontextbudget · Ein- und Ausgabe<input type="number" min="128" max="2097152" value={profile.context_tokens} onChange={e=>field('context_tokens',Number(e.target.value))}/></label>
|
||||
<label>Temperatur · leer = nicht senden<input type="number" min="0" max="2" step="0.1" value={profile.temperature??''} onChange={e=>field('temperature',e.target.value===''?null:Number(e.target.value))}/></label>
|
||||
<label>Denkaufwand · nur bei Unterstützung<select value={profile.reasoning_effort} onChange={e=>field('reasoning_effort',e.target.value)}>{['','none','minimal','low','medium','high','xhigh','max'].map(v=><option key={v} value={v}>{v||'Nicht senden'}</option>)}</select></label>
|
||||
<label>Zeitlimit in Sekunden<input type="number" min="5" max="90" value={profile.timeout_seconds} onChange={e=>field('timeout_seconds',Number(e.target.value))}/></label>
|
||||
</div>
|
||||
<button type="button" disabled={busy} onClick={()=>void run(async()=>{const result=await getAIModels(profile.provider);setModels(result.data);setNotice(`${result.data.length} Modelle geladen. Verbindung erfolgreich. Ein Testlauf erzeugt zusätzliche, erfasste Kosten.`)})}>Modellliste laden / Verbindung prüfen</button>
|
||||
<p className="muted">Modellnamen und unterstützte Parameter beim Anbieter prüfen. Das Kontextbudget wird vor dem Versand konservativ begrenzt. Für zwölfteilige Tests ein ausreichend großes Profil konfigurieren.</p>
|
||||
<h4>Preise in USD pro Million Tokens</h4><div className="ai-form-grid">{([['input_microusd_per_million','Eingabe'],['cached_input_microusd_per_million','Gecachte Eingabe'],['output_microusd_per_million','Ausgabe']]as const).map(([key,label])=><label key={key}>{label}<input type="number" min="0" max="1000" step="0.000001" value={profile[key]/1000000} onChange={e=>field(key,micro(e.target.value))}/></label>)}</div>
|
||||
<label><input type="checkbox" checked={profile.pricing_set} onChange={e=>field('pricing_set',e.target.checked)}/>Preise mit aktuellen Anbieterpreisen abgeglichen</label>
|
||||
<label><input type="checkbox" checked={profile.json_schema} disabled={profile.provider!=='mistral'} onChange={e=>field('json_schema',e.target.checked)}/>JSON-Schemamodus · nur bei unterstütztem Mistral-Modell</label>
|
||||
<label><input type="checkbox" checked={profile.enabled} onChange={e=>field('enabled',e.target.checked)}/>Profil für neue KI-Aufträge aktivieren</label>
|
||||
{error&&<p className="form-error" role="alert">{error}</p>}
|
||||
<button type="button" className="primary-button" disabled={busy} onClick={()=>void run(async()=>{await saveAIProfile(profile);await refresh();setNotice('Neue Profilversion gespeichert. Vor Freigabe mit richtigen und falschen Antworten testen.');})}>Modellprofil speichern</button>
|
||||
<details><summary>Verwendeter Systemprompt und Ausgabeschema</summary><pre>{settings.prompts[action]}</pre><pre>{settings.schemas[action]||'Kein separates Schema; Vertragsprüfung in Go.'}</pre></details>
|
||||
{action==='evaluate_course_attempt'&&<><button type="button" disabled={busy} onClick={()=>void run(async()=>{setTestResult(await testAIQuality(courseRequestID()));await refreshUsage();await refresh()})}>Bewertungsqualität prüfen · 2 kostenpflichtige Testfälle</button><button type="button" disabled={busy} onClick={()=>void run(async()=>{setTestResult(await testAIQuality(courseRequestID(),'writing'));await refreshUsage();await refresh()})}>Schreibbewertung prüfen · 2 kostenpflichtige Testfälle</button></>}
|
||||
{testResult!=null&&<pre>{JSON.stringify(testResult,null,2)}</pre>}
|
||||
<details><summary>Gespeichertes Profil testen · erzeugt API-Kosten</summary><p>Hier nur den Inhalt von input einfügen. Der Aufruf verändert keinen Kursfortschritt und wird auch für ein deaktiviertes Profil erfasst. Änderungen am Profil zuerst speichern.</p><textarea rows={8} value={input} onChange={e=>setInput(e.target.value)} aria-label="KI-Testeingabe"/>
|
||||
<button type="button" disabled={busy||!input.trim()} onClick={()=>void run(async()=>{const result=await testAI(action,JSON.parse(input),courseRequestID());setTestResult(result);await refreshUsage();await refresh();})}>Kostenpflichtigen Test ausführen</button></details>
|
||||
</>}
|
||||
</div></>}
|
||||
<div className="panel view-stack"><h3>KI-Verbrauch</h3><div className="ai-form-grid">{(['from','to','provider','model','user','action']as const).map(key=><label key={key}>{{from:'Von',to:'Bis',provider:'Anbieter',model:'Modell',user:'Nutzer-ID',action:'Arbeitsschritt'}[key]}{key==='provider'||key==='action'?<select value={filters[key]} onChange={e=>{setOffset(0);setFilters({...filters,[key]:e.target.value})}}><option value="">Alle</option>{Object.entries(key==='provider'?{deepseek:'DeepSeek',mistral:'Mistral'}:aiActions).map(([id,label])=><option key={id} value={id}>{label}</option>)}</select>:<input type={key==='from'||key==='to'?'datetime-local':'text'} value={filters[key]} onChange={e=>{setOffset(0);setFilters({...filters,[key]:e.target.value})}}/>}</label>)}</div>
|
||||
<button type="button" disabled={busy} onClick={()=>void run(async()=>{await refreshUsage();await refresh()})}>Verbrauch aktualisieren</button>
|
||||
{(detail||detailLoading||detailError)&&<div ref={detailPanel} tabIndex={-1} className="panel view-stack" role="region" aria-label="KI-Aufrufdetails" aria-busy={detailLoading}><h3>Aufrufdetails</h3><button type="button" disabled={detailLoading} onClick={closeDetail}>Schließen</button>{detailLoading&&<p role="status">Aufrufdetails werden geladen…</p>}{detailError&&<p className="form-error" role="alert">{detailError}</p>}{detail&&<><pre>{JSON.stringify(detail,null,2)}</pre>
|
||||
{detail.cost_microusd==null&&detail.status!=='running'&&<><p>Unbekannten Verbrauch anhand der Anbieterrechnung abgleichen. Der Eintrag und die Begründung bleiben erhalten.</p><label>Tatsächliche Kosten in USD<input type="number" min="0" step="0.000001" value={resolveCost} onChange={e=>setResolveCost(e.target.value)}/></label><label>Begründung<input value={reason} onChange={e=>setReason(e.target.value)}/></label><button type="button" disabled={busy||resolveCost===''||reason.length<5} onClick={()=>void run(async()=>{await resolveAICall(detail.id,micro(resolveCost),reason);setDetail(null);await refreshUsage();await refresh()})}>Abgleich speichern</button></>}
|
||||
</>}</div>}
|
||||
{usage&&<><p>{usage.total} Aufrufe · Eingabe {usage.input_tokens.toLocaleString('de-DE')} · Ausgabe {usage.output_tokens.toLocaleString('de-DE')} Tokens</p><p>Geschätzte Kosten {dollars(usage.estimated_cost_microusd)} · offene Reservierungen {dollars(usage.reserved_microusd)} · Verbrauch unbekannt bei {usage.unknown_usage_calls} Aufrufen</p>
|
||||
<div className="admin-table-wrap"><table className="admin-table"><thead><tr><th>Zeit / Nutzer</th><th>Modell / Schritt</th><th>Status</th><th>Tokens Ein / Aus</th><th>Kosten</th><th>Details</th></tr></thead><tbody>{usage.calls.map(c=><tr key={c.id}><td>{new Date(c.created_at).toLocaleString('de-DE')}<small>{c.user_id}</small></td><td>{c.provider} · {c.model}<small>{aiActions[c.action]??c.action} · Profil v{c.profile.version}{c.test?' · Test':''}</small></td><td>{c.status}<small>{c.duration_ms} ms · Versuch {c.attempt}</small></td><td>{c.usage?`${c.usage.input_tokens} / ${c.usage.output_tokens}`:'Unbekannt'}</td><td>{c.cost_microusd==null?`Reserviert ${dollars(c.reserved_microusd)}`:dollars(c.cost_microusd)}</td><td><button type="button" disabled={busy} onClick={e=>void openDetail(c.id,e.currentTarget)}>Anzeigen</button></td></tr>)}</tbody></table></div>
|
||||
<div className="action-row"><button type="button" disabled={offset===0} onClick={()=>setOffset(Math.max(0,offset-50))}>Zurück</button><span>{offset+1}–{Math.min(offset+50,usage.total)} von {usage.total}</span><button type="button" disabled={offset+50>=usage.total} onClick={()=>setOffset(offset+50)}>Weiter</button></div></>}
|
||||
</div>
|
||||
|
||||
</section>
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { answerCourseAudio, answerCourseTask, courseRequestID, courseSkillNames, getAdaptiveAudio, type AdaptiveAttempt, type AdaptiveTask } from '../api/adaptive';
|
||||
import { AudioRecorder } from './AudioRecorder';
|
||||
|
||||
type Props = { task: AdaptiveTask; attempt: AdaptiveAttempt | null; locked: boolean; onAttempt: (attempt: AdaptiveAttempt) => void; onBusy: (value: boolean) => void; onRecording: (value: boolean) => void };
|
||||
export function AdaptiveExercise({ task, attempt, locked, onAttempt, onRecording, onBusy }: Props) {
|
||||
const [answer, setAnswer] = useState('');
|
||||
const [recording, setRecording] = useState(false);
|
||||
const [audio, setAudio] = useState<Blob | null>(null);
|
||||
const [audioURL, setAudioURL] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
useEffect(() => { onBusy(busy); return () => onBusy(false); }, [busy, onBusy]);
|
||||
const requestID = useRef<string | null>(null);
|
||||
const playback = useRef<{ audio: HTMLAudioElement; url: string } | null>(null);
|
||||
function stopPlayback() { if (playback.current) { playback.current.audio.pause(); URL.revokeObjectURL(playback.current.url); playback.current = null; } }
|
||||
useEffect(() => () => stopPlayback(), []);
|
||||
useEffect(() => { if (!audio) { setAudioURL(''); return; } const url = URL.createObjectURL(audio); setAudioURL(url); return () => URL.revokeObjectURL(url); }, [audio]);
|
||||
const isSpeech = task.kind === 'repeat_sentence' || task.kind === 'free_speech';
|
||||
const examAnswered = Boolean(task.exam_id && attempt);
|
||||
const disabled = locked || busy || examAnswered || attempt?.status === 'pending';
|
||||
async function play() {
|
||||
setError(''); setBusy(true);
|
||||
try { stopPlayback(); const blob = await getAdaptiveAudio(task.id); const url = URL.createObjectURL(blob); const player = new Audio(url); playback.current = { audio: player, url }; player.onended = stopPlayback; player.onerror = () => { stopPlayback(); setError('Audio konnte nicht abgespielt werden.'); }; await player.play(); }
|
||||
catch (err) { stopPlayback(); setError(err instanceof Error ? err.message : 'Audio nicht verfügbar.'); }
|
||||
finally { setBusy(false); }
|
||||
}
|
||||
async function submit() {
|
||||
if (disabled || recording || (isSpeech ? !audio : !answer.trim())) return;
|
||||
setBusy(true); setError('');
|
||||
try {
|
||||
requestID.current ??= courseRequestID();
|
||||
const result = isSpeech ? await answerCourseAudio(task.id, audio!, requestID.current) : await answerCourseTask(task.id, answer, requestID.current);
|
||||
requestID.current = null; onAttempt(result.attempt); setAudio(null);
|
||||
} catch (err) { setError(err instanceof Error ? err.message : 'Antwort konnte nicht gespeichert werden.'); }
|
||||
finally { setBusy(false); }
|
||||
}
|
||||
return <div className="view-stack">
|
||||
<p className="eyebrow">{courseSkillNames[task.skill]} · {task.source === 'curated' ? 'Aus geprüftem Aufgabenbestand' : task.source === 'ai' ? 'Mit KI erstellt' : task.source === 'flowise' ? 'Mit Flowise erstellt' : 'Geprüfte Ersatzaufgabe'}{task.review ? ' · Wiederholung' : ''}</p>
|
||||
<h2>{task.prompt}</h2>
|
||||
{task.kind==='free_speech'&&<p className="muted">Inhalt und Sprache werden von der KI bewertet. Der Azure-Aussprachewert wird getrennt angezeigt.</p>}
|
||||
{task.passage && <p className="course-passage" lang={task.target_language} dir="auto">{task.passage}</p>}
|
||||
{task.reference_text && <p className="target-text" lang={task.target_language} dir="auto">{task.reference_text}</p>}
|
||||
{(task.skill === 'listening' || task.kind === 'repeat_sentence') && <button type="button" className="ghost-button" disabled={busy || recording} onClick={() => void play()}>Anhören</button>}
|
||||
{task.kind === 'choice' && <div className="course-options" role="group" aria-label="Antwortmöglichkeiten">{task.options?.map((option) => <label key={option.id} className="course-option" dir="auto"><input type="radio" name={task.id} checked={answer === option.id} value={option.id} disabled={disabled} onChange={() => { setAnswer(option.id); requestID.current = null; }} />{option.label}</label>)}</div>}
|
||||
{(task.kind === 'free_text' || task.kind === 'short_text') && <label>Deine Antwort<textarea rows={task.kind === 'free_text' ? 5 : 2} maxLength={10000} lang={task.target_language} dir="auto" disabled={disabled} value={answer} onChange={(event) => { setAnswer(event.target.value); requestID.current = null; }} /></label>}
|
||||
{isSpeech && <>
|
||||
<p className="muted">Bis zu 30 Sekunden. Du kannst die Aufnahme vor dem Absenden anhören.</p>
|
||||
<AudioRecorder maxSeconds={30} disabled={disabled} onRecorded={setAudio} onRecordingStart={() => { setAudio(null); requestID.current = null; stopPlayback(); }} onRecordingChange={(value) => { setRecording(value); onRecording(value); }} />
|
||||
{audioURL && <audio controls src={audioURL} />}
|
||||
</>}
|
||||
<button type="button" className="primary-button" onClick={() => void submit()} disabled={disabled || recording || (isSpeech ? !audio : !answer.trim())}>{busy ? 'Antwort wird verarbeitet…' : task.exam_id ? 'Testantwort speichern' : 'Antwort prüfen'}</button>
|
||||
{error && <p className="form-error" role="alert">{error}</p>}
|
||||
{attempt && <div className="course-feedback" role="status">
|
||||
{attempt.demo && <p>Demo-Messung: zählt nicht als Lernnachweis.</p>}
|
||||
{task.exam_id && !attempt.evaluation ? <p>Testantwort gespeichert. Das Feedback erscheint, sobald alle zwölf Antworten bewertet sind.</p> : attempt.status === 'pending' ? <p>Antwort gespeichert. Der Lehrer-Agent bewertet sie.</p> : attempt.status === 'ungraded' ? <p>Antwort gespeichert – ohne verbindliche Note. Eine KI-Bewertung kann später angefordert werden.</p> : attempt.status === 'failed' ? <p>Die Bewertung steht noch aus. Du kannst sie erneut anfordern.</p> : attempt.evaluation && <><strong>{task.kind==='free_speech'?'Inhalt und Sprache: ':''}{Math.round(attempt.evaluation.score)} / 100 · {attempt.evaluation.verdict === 'correct' ? 'Richtig' : attempt.evaluation.verdict === 'partial' ? 'Teilweise richtig' : 'Noch üben'}</strong><p>{attempt.evaluation.feedback}</p>{attempt.evaluation.issues?.map((issue, i) => <p key={i}>{issue}</p>)}</>}
|
||||
{task.kind==='free_speech'&&<p>Erkannter Text: {attempt.answer}</p>}
|
||||
{attempt.speech && <p>Aussprache: {Math.round(attempt.speech.overall_score)} / 100</p>}
|
||||
{task.answer_key && <><p>{task.answer_key.explanation}</p>{attempt?.status === 'ungraded' && <><p>Zum Selbstvergleich, ohne Benotung:</p><ul>{task.answer_key.rubric?.map((rule,i)=><li key={i}>{rule}</li>)}</ul></>}{task.answer_key.reference_answer && <p lang={task.target_language} dir="auto">Beispiel: {task.answer_key.reference_answer}</p>}{task.audio_text && <p lang={task.target_language} dir="auto">Hörtext: {task.audio_text}</p>}</>}
|
||||
</div>}
|
||||
</div>;
|
||||
}
|
||||
@@ -8,9 +8,10 @@ type Props = {
|
||||
disabled?: boolean;
|
||||
buttonLabel?: string;
|
||||
secondary?: boolean;
|
||||
maxSeconds?: number;
|
||||
};
|
||||
|
||||
export function AudioRecorder({ onRecorded, onRecordingStart, onRecordingChange, disabled, buttonLabel = 'Aufnehmen', secondary }: Props) {
|
||||
export function AudioRecorder({ onRecorded, onRecordingStart, onRecordingChange, disabled, buttonLabel = 'Aufnehmen', secondary, maxSeconds }: Props) {
|
||||
const [recording, setRecording] = useState(false);
|
||||
const [starting, setStarting] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
@@ -21,6 +22,7 @@ export function AudioRecorder({ onRecorded, onRecordingStart, onRecordingChange,
|
||||
const contextRef = useRef<AudioContext | null>(null);
|
||||
const processorRef = useRef<ScriptProcessorNode | null>(null);
|
||||
const sourceRef = useRef<MediaStreamAudioSourceNode | null>(null);
|
||||
const stopTimer = useRef<number | undefined>(undefined);
|
||||
const chunks = useRef<Float32Array[]>([]);
|
||||
const sampleRate = useRef(44100);
|
||||
|
||||
@@ -28,6 +30,7 @@ export function AudioRecorder({ onRecorded, onRecordingStart, onRecordingChange,
|
||||
mountedRef.current = true;
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
window.clearTimeout(stopTimer.current);
|
||||
streamRef.current?.getTracks().forEach((track) => track.stop());
|
||||
void contextRef.current?.close();
|
||||
};
|
||||
@@ -66,6 +69,7 @@ export function AudioRecorder({ onRecorded, onRecordingStart, onRecordingChange,
|
||||
recordingRef.current = true;
|
||||
setRecording(true);
|
||||
onRecordingStart?.();
|
||||
if (maxSeconds) stopTimer.current = window.setTimeout(stop, maxSeconds * 1000);
|
||||
} catch (err) {
|
||||
stream?.getTracks().forEach((track) => track.stop());
|
||||
if (audioContext) void audioContext.close();
|
||||
@@ -80,6 +84,7 @@ export function AudioRecorder({ onRecorded, onRecordingStart, onRecordingChange,
|
||||
function stop() {
|
||||
if (!recordingRef.current) return;
|
||||
recordingRef.current = false;
|
||||
window.clearTimeout(stopTimer.current);
|
||||
processorRef.current?.disconnect();
|
||||
sourceRef.current?.disconnect();
|
||||
streamRef.current?.getTracks().forEach((track) => track.stop());
|
||||
@@ -96,7 +101,7 @@ export function AudioRecorder({ onRecorded, onRecordingStart, onRecordingChange,
|
||||
return;
|
||||
}
|
||||
const downsampled = downsampleBuffer(merged, sampleRate.current, 16000);
|
||||
const wav = encodeWav(downsampled, 16000);
|
||||
const wav = encodeWav(maxSeconds ? downsampled.slice(0, maxSeconds * 16000) : downsampled, 16000);
|
||||
onRecorded(new Blob([wav], { type: 'audio/wav' }));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { fetchPronunciationProfile, type PronunciationProfile, type PronunciationTarget } from '../api/pronunciation';
|
||||
const states:Record<string,string>={limited:'Wenige Nachweise – nachprüfen',observed:'Noch uneinheitlich',needs_practice:'Wiederholt schwierig',improved:'Verbessert',stable:'Stabil mit Wiederholung'};
|
||||
const trends:Record<string,string>={insufficient:'Entwicklung noch nicht ausreichend belegt',improving:'Entwicklung verbessert',declining:'Zuletzt wieder schwieriger',steady:'Zuletzt ähnlich'};
|
||||
export function PronunciationOverview(){
|
||||
const [profile,setProfile]=useState<PronunciationProfile|null>(null),[error,setError]=useState(''),[all,setAll]=useState(false);
|
||||
useEffect(()=>{let valid=true;fetchPronunciationProfile().then(p=>{if(valid)setProfile(p)}).catch(e=>{if(valid)setError(e instanceof Error?e.message:'Ausspracheprofil nicht verfügbar')});return()=>{valid=false}},[]);
|
||||
if(error)return <section className="panel result-panel" aria-label="Ausspracheprofil"><h2>Ausspracheprofil</h2><p className="form-error" role="alert">{error}</p></section>;
|
||||
if(!profile)return <section className="panel result-panel" aria-label="Ausspracheprofil"><p>Lautprofil wird geladen…</p></section>;
|
||||
function group(kind:PronunciationTarget['kind'],title:string){
|
||||
const targets=profile!.targets.filter(t=>t.kind===kind);
|
||||
return <section className="panel result-panel"><h3>{title}</h3>{!targets.length?<p className="muted">Noch keine bestätigten Messungen in diesem Bereich.</p>:<div className="view-stack">{(all?targets:targets.slice(0,6)).map(t=><article className="pronunciation-target" key={t.key}>
|
||||
<strong>{kind==='phoneme'?`/${t.symbol}/`:t.symbol}</strong> <span>{states[t.state]??t.state}</span>
|
||||
<p>{kind==='omission'?`${100-Math.round(t.mean)} % gewichteter Auslassungsanteil`:`${Math.round(t.mean)} / 100`} · {t.samples} unabhängige Beobachtung{t.samples===1?'':'en'} · {t.words} Wortkontext{t.words===1?'':'e'} · {t.tasks} Aufgabe{t.tasks===1?'':'n'}</p>
|
||||
<p className="muted">{trends[t.trend]??t.trend}. Zuletzt: {new Date(t.last_seen).toLocaleDateString('de-DE')}.</p>
|
||||
{kind==='phoneme'&&<p>Beispielwörter: {t.examples.slice(0,5).map(e=>`${e.word} (${Math.round(e.mean)} / 100)`).join(', ')}</p>}
|
||||
{t.next_review&&<p>{t.review_due?'Wiederholung fällig':'Nächste Wiederholung'}: {new Date(t.next_review).toLocaleDateString('de-DE')}</p>}
|
||||
</article>)}</div>}</section>;
|
||||
}
|
||||
return <section className="view-stack" aria-label="Ausspracheprofil"><header><h2>Dein Ausspracheprofil · {profile.language}</h2><p>Echte Azure-Nachsprechmessungen aus Aussprache und Kurs werden zusammen betrachtet. Neuere Ergebnisse zählen stärker; ein einzelner Ausreißer ergibt noch kein sicheres Lautproblem.</p><p>{profile.confirmed_recordings} berücksichtigte Aufnahmen im Zeitfenster von {profile.window_days} Tagen. Wiederholungen derselben Aufgabe am selben Tag zählen je Wort oder Laut als eine Beobachtung.</p></header>
|
||||
{profile.unverified_history>0&&<p className="muted">{profile.unverified_history} ältere Versuche bleiben im Verlauf erhalten. Ihre Messherkunft ist nicht belegt; sie bestimmen dieses Profil nicht.</p>}
|
||||
{!profile.targets.length&&<p>Für dein neues Lautprofil fehlen noch bestätigte Messungen. Sprich einen Satz im Aussprachebereich nach, um zu beginnen.</p>}
|
||||
{group('phoneme','Laute über verschiedene Wörter hinweg')}{group('word','Wörter')}
|
||||
{profile.targets.some(t=>t.kind==='omission')&&group('omission','Vollständigkeit – ausgelassene Wörter')}
|
||||
{profile.targets.length>6&&<button type="button" onClick={()=>setAll(!all)}>{all?'Weniger anzeigen':'Alle Beobachtungen anzeigen'}</button>}
|
||||
<p className="muted">Die Zustände sind Lernhilfen, keine Zertifizierung. Wortgenauigkeit und Lautwerte sind keine statistischen Wahrscheinlichkeiten.</p>
|
||||
</section>;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AIAdmin } from '../components/AIAdmin';
|
||||
import { useEffect, useState, type FormEvent } from 'react';
|
||||
import { fetchAdminOverview, fetchAdminUsers } from '../api/admin';
|
||||
import type { AdminOverview, AdminUserPage } from '../api/types';
|
||||
@@ -52,7 +53,7 @@ export function AdminPage() {
|
||||
<div className="panel metric"><span>Nutzer gesamt</span><strong>{overview?.users_total ?? '–'}</strong></div>
|
||||
<div className="panel metric"><span>Aktiv in 7 Tagen</span><strong>{overview?.users_active_7_days ?? '–'}</strong></div>
|
||||
<div className="panel metric"><span>Sprechversuche</span><strong>{overview?.attempts_total ?? '–'}</strong></div>
|
||||
<div className="panel metric"><span>Flowise-Übungen</span><strong>{overview?.exercises_generated ?? '–'}</strong></div>
|
||||
<div className="panel metric"><span>KI-Ausspracheübungen</span><strong>{overview?.exercises_generated ?? '–'}</strong></div>
|
||||
<div className="panel metric"><span>Ø Bewertung</span><strong>{overview ? Math.round(overview.average_score) : '–'}</strong></div>
|
||||
</section>
|
||||
|
||||
@@ -99,6 +100,7 @@ export function AdminPage() {
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<AIAdmin />
|
||||
<section className="panel admin-product">
|
||||
<div>
|
||||
<p className="eyebrow">Produktbetrieb</p>
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { request } from '../api/client';
|
||||
import {
|
||||
courseSkills, courseSkillNames, courseRequestID, getCourseCatalog, getCourseHistory, getAdaptiveTask,
|
||||
createCourseTask, getCourseJob, retryCourseJob, getCourseAttempt, retryCourseAttempt, createCourseExam, getCourseExam,
|
||||
type CourseCatalog, type CourseJob, type AdaptiveTask, type AdaptiveAttempt, type AdaptiveExam
|
||||
} from '../api/adaptive';
|
||||
import { AdaptiveExercise } from '../components/AdaptiveExercise';
|
||||
import { LegacyCoursePage } from './LegacyCoursePage';
|
||||
|
||||
const stageNames: Record<string, string> = { queued: 'Auftrag gespeichert', starting: 'Vorbereitung', analyzing: 'Lernstand wird analysiert', planning: 'Lernauftrag wird erstellt', generating_and_reviewing: 'Aufgabe wird erstellt und fachlich geprüft', evaluating: 'Antwort wird bewertet', generating_and_reviewing_exam: 'Zwölf Testaufgaben werden erstellt und geprüft' };
|
||||
type SavedView = { module: string; task?: string; job?: string; exam?: string };
|
||||
export function CoursePage() {
|
||||
const [catalog, setCatalog] = useState<CourseCatalog | null>(null);
|
||||
const [moduleID, setModuleID] = useState('');
|
||||
const [skill, setSkill] = useState('');
|
||||
const [task, setTask] = useState<AdaptiveTask | null>(null);
|
||||
const [attempt, setAttempt] = useState<AdaptiveAttempt | null>(null);
|
||||
const [job, setJob] = useState<CourseJob | null>(null);
|
||||
const [exam, setExam] = useState<AdaptiveExam | null>(null);
|
||||
const [history, setHistory] = useState<AdaptiveTask[]>([]);
|
||||
const [hasMore, setHasMore] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [recording, setRecording] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [legacy, setLegacy] = useState(false);
|
||||
const [restored, setRestored] = useState(false);
|
||||
const [revision, setRevision] = useState(0);
|
||||
const generationID = useRef<string | null>(null);
|
||||
const examRequestID = useRef<string | null>(null);
|
||||
const exerciseRef = useRef<HTMLElement | null>(null);
|
||||
const active = useRef(true);
|
||||
const jobRunning = Boolean(job && (job.status === 'queued' || job.status === 'running'));
|
||||
const locked = busy || recording || submitting || jobRunning;
|
||||
const storeKey = catalog ? `speech_course_v2:${catalog.profile.id}` : '';
|
||||
function showError(err: unknown) { if (active.current) setError(err instanceof Error ? err.message : 'Der Kurs konnte nicht geladen werden.'); }
|
||||
async function openTask(id: string) {
|
||||
const result = await getAdaptiveTask(id);
|
||||
if (!active.current) return;
|
||||
setTask(result.task); setAttempt(result.attempt); setError('');
|
||||
}
|
||||
async function refreshCatalog() {
|
||||
const result = await getCourseCatalog(); if (active.current) setCatalog(result);
|
||||
}
|
||||
useEffect(() => { active.current = true; return () => { active.current = false; }; }, []);
|
||||
useEffect(() => {
|
||||
let valid = true; setRestored(false); setError('');
|
||||
getCourseCatalog().then(async (loaded) => {
|
||||
if (!valid) return;
|
||||
setCatalog(loaded);
|
||||
let saved: SavedView | null = null;
|
||||
try { saved = JSON.parse(localStorage.getItem(`speech_course_v2:${loaded.profile.id}`) ?? 'null'); } catch { /* Ignore an invalid local view, never alter server data. */ }
|
||||
const selected = loaded.modules.find((m) => m.id === saved?.module)?.id ?? loaded.analysis?.recommended_module_id ?? loaded.modules[0]?.id ?? '';
|
||||
setModuleID(selected);
|
||||
if (saved?.exam) { try { const value = await getCourseExam(saved.exam); if (valid) setExam(value); } catch { /* The server rejects inaccessible or obsolete IDs. */ } }
|
||||
if (saved?.task) { try { const value = await getAdaptiveTask(saved.task); if (valid) { setTask(value.task); setAttempt(value.attempt); } } catch { /* Resume at the module if this task is unavailable. */ } }
|
||||
if (saved?.job) { try { const value = await getCourseJob(saved.job); if (valid) setJob(value); } catch { /* Keep the saved task and allow a new request. */ } }
|
||||
if (valid) setRestored(true);
|
||||
}).catch((err) => { if (valid) { showError(err); setRestored(true); } });
|
||||
return () => { valid = false; };
|
||||
}, [revision]);
|
||||
useEffect(() => {
|
||||
if (!restored || !storeKey) return;
|
||||
localStorage.setItem(storeKey, JSON.stringify({ module: moduleID, task: task?.id, job: job?.id, exam: exam?.id }));
|
||||
}, [restored, storeKey, moduleID, task?.id, job?.id, exam?.id]);
|
||||
useEffect(() => {
|
||||
if (!moduleID || !restored) return;
|
||||
let valid = true;
|
||||
setHistory([]); setHasMore(false);
|
||||
getCourseHistory(moduleID).then((result) => { if (valid) { setHistory(result.tasks); setHasMore(result.has_more); } }).catch((err) => { if (valid) showError(err); });
|
||||
return () => { valid = false; };
|
||||
}, [moduleID, restored, catalog?.profile.id]);
|
||||
useEffect(() => {
|
||||
if (!job) return;
|
||||
let valid = true; let timer: number | undefined;
|
||||
async function poll() {
|
||||
try {
|
||||
const current = await getCourseJob(job!.id); if (!valid) return;
|
||||
setJob(current);
|
||||
if (current.status === 'succeeded') {
|
||||
if (current.task_id) {
|
||||
const result = await getAdaptiveTask(current.task_id); if (!valid) return;
|
||||
setTask({ ...result.task, review: current.review }); setAttempt(result.attempt);
|
||||
if ((result.task.source === 'flowise' || result.task.source === 'ai' || result.task.source === 'curated')) setHistory((old) => [result.task, ...old.filter((item) => item.id !== result.task.id)]);
|
||||
}
|
||||
if (current.kind === 'exam' && current.subject_id) { const result = await getCourseExam(current.subject_id); if (!valid) return; setExam(result); if (result.tasks[0]) { setTask(result.tasks[0]); setAttempt(null); } }
|
||||
setJob(null); await refreshCatalog();
|
||||
if (valid) requestAnimationFrame(() => exerciseRef.current?.scrollIntoView({ block: 'center', behavior: 'smooth' }));
|
||||
} else if (current.status === 'failed') { setError(current.error ?? 'Der Auftrag konnte nicht abgeschlossen werden.'); }
|
||||
else { timer = window.setTimeout(poll, 1200); }
|
||||
} catch (err) { if (valid) { showError(err); timer = window.setTimeout(poll, 4000); } }
|
||||
}
|
||||
void poll(); return () => { valid = false; window.clearTimeout(timer); };
|
||||
}, [job?.id, job?.status === 'failed']);
|
||||
useEffect(() => {
|
||||
if (!attempt || attempt.status !== 'pending') return;
|
||||
let valid = true; let timer: number | undefined;
|
||||
async function poll() {
|
||||
try {
|
||||
const result = await getCourseAttempt(attempt!.id); if (!valid) return;
|
||||
setAttempt(result);
|
||||
if (result.status === 'pending') timer = window.setTimeout(poll, 1500);
|
||||
else { const detail = await getAdaptiveTask(result.task_id); if (valid) { setTask(detail.task); setAttempt(detail.attempt); } await refreshCatalog(); }
|
||||
} catch (err) { if (valid) { showError(err); timer = window.setTimeout(poll, 4000); } }
|
||||
}
|
||||
void poll(); return () => { valid = false; window.clearTimeout(timer); };
|
||||
}, [attempt?.id, attempt?.status]);
|
||||
useEffect(() => {
|
||||
if (!exam) return;
|
||||
let valid = true; let timer: number | undefined;
|
||||
async function poll() {
|
||||
try {
|
||||
const value = await getCourseExam(exam!.id); if (!valid) return;
|
||||
setExam(value);
|
||||
if (value.status === 'completed') {
|
||||
setTask((old) => old?.exam_id === value.id ? value.tasks.find((t) => t.id === old.id) ?? old : old);
|
||||
setAttempt((old) => old?.exam_id === value.id ? value.attempts.find((a) => a.id === old.id) ?? old : old);
|
||||
}
|
||||
if (value.status === 'preparing' && value.preparation_job_id) setJob((old) => old?.id === value.preparation_job_id ? old : { id: value.preparation_job_id!, status: 'queued', stage: 'queued', kind: 'exam' });
|
||||
if (value.status === 'preparing' || value.status === 'in_progress' || value.attempts.some(a=>a.status==='pending') || value.summary_status === 'pending') timer = window.setTimeout(poll, 2500);
|
||||
} catch (err) { if (valid) { showError(err); timer = window.setTimeout(poll, 5000); } }
|
||||
}
|
||||
void poll(); return () => { valid = false; window.clearTimeout(timer); };
|
||||
}, [exam?.id, exam?.status, exam?.summary_status]);
|
||||
useEffect(() => {
|
||||
if (!catalog || catalog.task_mode === 'bank' || catalog.analysis?.facts_version === catalog.facts_version || catalog.analysis_job?.status === 'failed' || catalog.facts_version === 0) return;
|
||||
const timer = window.setTimeout(() => { void refreshCatalog().catch(showError); }, 3000);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [catalog]);
|
||||
async function generate() {
|
||||
if (locked || !moduleID) return; setBusy(true); setError('');
|
||||
try { generationID.current ??= courseRequestID(); const next = await createCourseTask(moduleID, skill, generationID.current); generationID.current = null; setExam(null); setJob(next); }
|
||||
catch (err) { showError(err); } finally { setBusy(false); }
|
||||
}
|
||||
async function changeLanguage(language: string) {
|
||||
if (locked) return; setBusy(true); setError('');
|
||||
try { await request('/me/preferences', { method: 'PATCH', body: JSON.stringify({ target_language: language, cefr_level: 'A1', daily_goal_minutes: catalog?.profile.daily_goal_minutes ?? 10 }) }); setTask(null); setAttempt(null); setJob(null); setExam(null); generationID.current = null; examRequestID.current = null; setRevision((n) => n + 1); }
|
||||
catch (err) { showError(err); } finally { setBusy(false); }
|
||||
}
|
||||
async function startExam() {
|
||||
if (locked) return; setBusy(true); setError('');
|
||||
try { examRequestID.current ??= courseRequestID(); const result = await createCourseExam(examRequestID.current); examRequestID.current = null; setExam(result.exam); setJob(result.job); setTask(null); setAttempt(null); }
|
||||
catch (err) { showError(err); } finally { setBusy(false); }
|
||||
}
|
||||
async function loadMore() {
|
||||
if (busy) return; setBusy(true);
|
||||
try { const result = await getCourseHistory(moduleID, history.length); setHistory((old) => [...old, ...result.tasks.filter((t) => !old.some((x) => x.id === t.id))]); setHasMore(result.has_more); }
|
||||
catch (err) { showError(err); } finally { setBusy(false); }
|
||||
}
|
||||
async function receivedAttempt(value: AdaptiveAttempt) {
|
||||
if (!active.current) return;
|
||||
setAttempt(value);
|
||||
try { if ((value.status === 'graded' || value.status === 'ungraded') && !value.exam_id) await openTask(value.task_id); await refreshCatalog(); if (exam) setExam(await getCourseExam(exam.id)); }
|
||||
catch (err) { showError(err); }
|
||||
}
|
||||
if (legacy) return <><button type="button" className="ghost-button" onClick={() => setLegacy(false)}>Zurück zum adaptiven Kurs</button><LegacyCoursePage /></>;
|
||||
if (!catalog) return <section className="panel"><p>{error || 'Lade A1-Kurs…'}</p>{error && <button type="button" onClick={() => setRevision((n) => n + 1)}>Erneut laden</button>}</section>;
|
||||
const selected = catalog.modules.find((m) => m.id === moduleID);
|
||||
const analysis = catalog.analysis?.modules.find((m) => m.module_id === moduleID);
|
||||
const progress = catalog.progress.filter((p) => p.module_id === moduleID);
|
||||
const inventory=(catalog.bank??[]).filter(p=>p.module_id===moduleID && (!skill||p.skill===skill));
|
||||
const evaluating = attempt?.status === 'pending';
|
||||
return <div className="view-stack">
|
||||
<header className="view-header"><div><p className="eyebrow">Adaptiver Sprachkurs · A1</p><h1>Dein A1-Kurs</h1><p className="muted">Sieben Module, sechs Lernbereiche und neue Aufgaben passend zu deinem Lernstand.</p></div>
|
||||
<label>Kurssprache<select disabled={locked} value={catalog.profile.target_language} onChange={(event) => void changeLanguage(event.target.value)}>{catalog.languages.map((l) => <option key={l.code} value={l.code}>{l.display_name}{catalog.enabled_languages.includes(l.code) ? '' : ' – Kurs noch nicht verfügbar'}</option>)}</select></label>
|
||||
</header>
|
||||
{catalog.modules.length === 0 ? <section className="panel"><p>Für diese Zielsprache ist noch kein geprüftes A1-Sprachpaket freigeschaltet. Dein bisheriger Lernstand bleibt gespeichert.</p></section> : <>
|
||||
<section className="panel course-analysis"><h2>Dein Lernstand</h2><p>{catalog.task_mode === 'bank' ? 'Die Auswahl nutzt deine gespeicherten Bewertungen. Noch neue Aufgaben haben Vorrang; bei Lernbedarf folgen passende Übungen und Wiederholungen. Unbenotete Antworten zählen nicht als bewerteter Lernnachweis.' : catalog.analysis?.summary ?? 'Noch keine KI-Lernanalyse vorhanden. Der Lehrer-Agent erstellt sie aus deinen gespeicherten Antworten.'}</p>
|
||||
{catalog.analysis && catalog.analysis.facts_version < catalog.facts_version && <p className="muted" role="status">Die Lernanalyse wird nach deiner letzten Antwort aktualisiert.</p>}
|
||||
{catalog.analysis_job?.status === 'failed' && <button type="button" onClick={() => void retryCourseJob(catalog.analysis_job!.id).then(refreshCatalog).catch(showError)}>Lernanalyse erneut anfordern</button>}
|
||||
{catalog.analysis && <p className="muted">KI-Einschätzung auf Basis gespeicherter Lernnachweise. Alle Module bleiben frei zugänglich.</p>}
|
||||
</section>
|
||||
<nav className="course-module-grid" aria-label="A1-Module">{catalog.modules.map((m) => <button type="button" key={m.id} disabled={locked} className={`panel course-module-card${moduleID === m.id ? ' selected' : ''}`} onClick={() => { setModuleID(m.id); setTask(null); setAttempt(null); setExam(null); setJob(null); setError(''); generationID.current = null; }}>
|
||||
<span className="eyebrow">Modul {m.order}{catalog.analysis?.recommended_module_id === m.id ? ' · Empfohlen' : ''}</span><strong>{m.title}</strong><span className="muted">{catalog.analysis?.modules.some((a) => a.module_id === m.id && a.ready_for_completion) ? 'Lernziel laut KI und Bereichsnachweisen erreicht' : 'Weiterlernen'}</span>
|
||||
</button>)}</nav>
|
||||
{selected && <section className="panel view-stack"><div><p className="eyebrow">Modul {selected.order}</p><h2>{selected.title}</h2><p className="muted">{selected.description}</p></div>
|
||||
{analysis && <div><p>{analysis.recommendation}</p><p className="muted">{analysis.reason}</p>{analysis.weaknesses?.map((weakness, i) => <p key={i}>Noch üben: {weakness}</p>)}</div>}
|
||||
<div className="course-area-grid" role="group" aria-label="Lernbereich"><button type="button" disabled={locked} className={skill === '' ? 'course-task active' : 'course-task'} onClick={() => setSkill('')}>KI-Empfehlung</button>{courseSkills.map((area) => <button type="button" disabled={locked} key={area} className={skill === area ? 'course-task active' : 'course-task'} onClick={() => { setSkill(area); generationID.current = null; }}>{courseSkillNames[area]}</button>)}</div>
|
||||
<div className="action-row"><button type="button" className="primary-button" disabled={locked} onClick={() => void generate()}>{jobRunning ? 'Aufgabe wird vorbereitet…' : 'Nächste Aufgabe'}</button>{selected.key === 'review_test' && <button type="button" className="ghost-button" disabled={locked} onClick={() => void startExam()}>Neuen A1-Test starten · 12 Aufgaben</button>}</div>
|
||||
<p className="muted">Du kannst beliebig weiterüben. Die Anzahl erzeugter Aufgaben entscheidet nicht über den Modulabschluss.</p>
|
||||
{job && <div role="status"><p>{stageNames[job.stage] ?? job.stage}</p>{job.status === 'failed' && <button type="button" disabled={busy} onClick={() => { setError(''); void retryCourseJob(job.id).then(setJob).catch(showError); }}>Auftrag erneut versuchen</button>}</div>}
|
||||
{error && <p className="form-error" role="alert">{error}</p>}
|
||||
{catalog.task_mode==='bank' && <p>Geprüfter Aufgabenbestand: {inventory.reduce((n,p)=>n+p.total,0)} Aufgaben · {inventory.reduce((n,p)=>n+p.unseen,0)} noch neu. Danach stehen Wiederholungen bereit.</p>}<div className="course-progress-grid">{courseSkills.map((area) => { const p = progress.find((x) => x.skill === area); return <div key={area}><strong>{courseSkillNames[area]}</strong><p>{p ? `${p.distinct_tasks} Aufgaben · ${p.attempts} Antworten · Ø ${Math.round(p.average_score)}/100` : 'Noch kein bewerteter Lernnachweis'}</p></div>; })}</div>
|
||||
</section>}
|
||||
{exam && <section className="panel view-stack" aria-label="A1-Test"><h2>A1-Test</h2><p>{exam.status === 'completed' ? 'Test abgeschlossen' : exam.status === 'submitted' ? 'Abgegeben – Bewertung ausstehend. Eine Gesamtnote erscheint nach der Bewertung aller offenen Antworten.' : `${exam.attempts.length} von 12 Antworten gespeichert. Feedback erscheint am Ende.`}</p>
|
||||
{exam.status === 'submitted' && <><button type="button" disabled={!catalog.grading_available || locked} onClick={() => { void (async()=>{try{ for(const a of exam.attempts.filter(a=>a.status==='ungraded'||a.status==='failed')) await retryCourseAttempt(a.id); }catch(err){showError(err);}finally{setExam(await getCourseExam(exam.id));}})().catch(showError); }}>Ausstehende Antworten bewerten</button>{!catalog.grading_available && <p>KI-Bewertung derzeit nicht verfügbar. Alle Antworten bleiben gespeichert.</p>}</>}
|
||||
{exam.status === 'completed' && <><div className="course-progress-grid">{courseSkills.map((area) => <p key={area}>{courseSkillNames[area]}: {Math.round(exam.scores?.[area] ?? 0)} / 100</p>)}</div><strong>Gesamtergebnis: {Math.round(exam.score ?? 0)} / 100</strong><p>{exam.summary}</p>{exam.summary_status === 'failed' && exam.summary_job_id && <button type="button" onClick={() => void retryCourseJob(exam.summary_job_id!).then(() => setExam({ ...exam, summary_status: 'pending' })).catch(showError)}>KI-Gesamteinschätzung erneut anfordern</button>}<p className="muted">Interne A1-Lerneinschätzung.</p></>}
|
||||
<div className="course-area-grid">{exam.tasks.map((t, i) => <button type="button" key={t.id} disabled={recording || submitting || busy} className={task?.id === t.id ? 'course-task active' : 'course-task'} onClick={() => void openTask(t.id).catch(showError)}>{i + 1}. {courseSkillNames[t.skill]} {exam.attempts.some((a) => a.task_id === t.id) ? '✓' : ''}</button>)}</div>
|
||||
</section>}
|
||||
<div className="course-layout"><nav className="panel course-task-list" aria-label="Gespeicherte Aufgaben"><h2>Deine Aufgaben</h2>{history.length === 0 && <p className="muted">Deine ausgewählten Aufgaben werden hier gespeichert.</p>}{history.map((item) => <button type="button" className={task?.id === item.id ? 'course-task active' : 'course-task'} key={item.id} disabled={recording || submitting || busy} onClick={() => { setExam(null); void openTask(item.id).catch(showError); }}><span>{courseSkillNames[item.skill]} · {item.prompt.slice(0, 65)}</span></button>)}{hasMore && <button type="button" disabled={busy} onClick={() => void loadMore()}>Weitere Aufgaben laden</button>}
|
||||
{catalog.exams.map((item) => <button type="button" key={item.id} disabled={locked} className="course-task" onClick={() => void getCourseExam(item.id).then((value) => { setExam(value); if (value.tasks[0]) void openTask(value.tasks[0].id).catch(showError); }).catch(showError)}>A1-Test · {item.status === 'completed' ? 'Ergebnis' : 'Fortsetzen'}</button>)}
|
||||
</nav><section ref={exerciseRef} className="panel course-exercise" aria-label="Aktuelle Kursaufgabe" aria-live="polite">{task ? <><AdaptiveExercise key={task.id} task={task} attempt={attempt} locked={jobRunning} onAttempt={(a) => void receivedAttempt(a)} onRecording={setRecording} onBusy={setSubmitting} />{(attempt?.status === 'failed' || attempt?.status === 'ungraded') && <button type="button" disabled={catalog.task_mode === 'bank' && !catalog.grading_available} onClick={() => void retryCourseAttempt(attempt.id).then(() => setAttempt({ ...attempt, status: 'pending' })).catch(showError)}>{attempt.status === 'ungraded' ? 'Bewertung anfordern' : 'Bewertung erneut anfordern'}</button>}{attempt?.status === 'ungraded' && !catalog.grading_available && <p className="muted">Die KI-Bewertung ist derzeit nicht verfügbar. Du kannst deine Antwort ohne Benotung mit dem Beispiel vergleichen.</p>}{evaluating && <p className="muted">Die Antwort bleibt gespeichert, auch wenn du die Seite verlässt.</p>}</> : <p className="muted">Wähle ein Modul und fordere deine nächste Aufgabe an.</p>}</section></div>
|
||||
</>}
|
||||
<button type="button" className="link-button" disabled={locked} onClick={() => setLegacy(true)}>Bisherigen festen Kurs öffnen</button>
|
||||
</div>;
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { ApiError } from '../api/client';
|
||||
import {
|
||||
fetchDebugAzure,
|
||||
fetchDebugDB,
|
||||
fetchDebugFlowise,
|
||||
fetchDebugAI,
|
||||
fetchDebugRuntime,
|
||||
fetchDebugStatus,
|
||||
type DebugCheck,
|
||||
@@ -22,7 +22,7 @@ type DebugError = {
|
||||
export function DebugPage() {
|
||||
const [status, setStatus] = useState<DebugStatus | null>(null);
|
||||
const [db, setDB] = useState<DebugDB | null>(null);
|
||||
const [flowise, setFlowise] = useState<DebugCheck | null>(null);
|
||||
const [ai, setAI] = useState<DebugCheck | null>(null);
|
||||
const [azure, setAzure] = useState<DebugCheck | null>(null);
|
||||
const [runtime, setRuntime] = useState<Record<string, unknown> | null>(null);
|
||||
const [error, setError] = useState<DebugError | null>(null);
|
||||
@@ -39,7 +39,7 @@ export function DebugPage() {
|
||||
const next = await fetchDebugStatus();
|
||||
setStatus(next);
|
||||
setDB(next.checks.db);
|
||||
setFlowise(next.checks.flowise);
|
||||
setAI(next.checks.ai);
|
||||
setAzure(next.checks.azure);
|
||||
const runtimeResponse = await fetchDebugRuntime();
|
||||
setRuntime(runtimeResponse.runtime);
|
||||
@@ -54,8 +54,8 @@ export function DebugPage() {
|
||||
await runCheck(async () => setDB((await fetchDebugDB()).db));
|
||||
}
|
||||
|
||||
async function runFlowise() {
|
||||
await runCheck(async () => setFlowise((await fetchDebugFlowise()).flowise));
|
||||
async function runAI() {
|
||||
await runCheck(async () => setAI((await fetchDebugAI()).ai));
|
||||
}
|
||||
|
||||
async function runAzure() {
|
||||
@@ -99,7 +99,7 @@ export function DebugPage() {
|
||||
<section className="debug-grid">
|
||||
<DebugCheckCard icon={<Database size={21} />} title="Datenbank" check={dbToCheck(db)} onRefresh={runDB} />
|
||||
<DebugCheckCard icon={<Waves size={21} />} title="Azure Speech" check={azure} onRefresh={runAzure} />
|
||||
<DebugCheckCard icon={<Activity size={21} />} title="Flowise" check={flowise} onRefresh={runFlowise} />
|
||||
<DebugCheckCard icon={<Activity size={21} />} title="KI-Anbindung" check={ai} onRefresh={runAI} />
|
||||
<DebugObjectCard icon={<Server size={21} />} title="Runtime" value={runtime} />
|
||||
</section>
|
||||
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { fetchCourseAudio, fetchCourseModule, fetchCourseModules, fetchCoursePractice, nextCoursePractice, submitCourseAnswer } from '../api/course';
|
||||
import { fetchExerciseAudio } from '../api/lessons';
|
||||
import { submitAttempt } from '../api/practice';
|
||||
import type { AttemptResponse, CourseAttemptResult, CourseModuleDetail, CourseTask } from '../api/types';
|
||||
import { AudioRecorder } from '../components/AudioRecorder';
|
||||
|
||||
const skillNames: Record<CourseTask['skill'], string> = {
|
||||
vocabulary: 'Wortschatz', listening: 'Hören', reading: 'Lesen', grammar: 'Grammatik',
|
||||
writing: 'Schreiben', pronunciation: 'Aussprache'
|
||||
};
|
||||
|
||||
export function LegacyCoursePage() {
|
||||
const [detail, setDetail] = useState<CourseModuleDetail | null>(null);
|
||||
const [practiceTasks, setPracticeTasks] = useState<CourseTask[]>([]);
|
||||
const [practiceTask, setPracticeTask] = useState<CourseTask | null>(null);
|
||||
const [practiceNotice, setPracticeNotice] = useState('');
|
||||
const [practiceError, setPracticeError] = useState('');
|
||||
const exerciseRef = useRef<HTMLElement | null>(null);
|
||||
const [practiceLoading, setPracticeLoading] = useState(true);
|
||||
const [generating, setGenerating] = useState(false);
|
||||
const requestIdRef = useRef<string | null>(null);
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const [selectedId, setSelectedId] = useState('');
|
||||
const [answer, setAnswer] = useState('');
|
||||
const [result, setResult] = useState<CourseAttemptResult | null>(null);
|
||||
const [pronResult, setPronResult] = useState<AttemptResponse | null>(null);
|
||||
const [recorded, setRecorded] = useState<Blob | null>(null);
|
||||
const [recordedUrl, setRecordedUrl] = useState('');
|
||||
const [recording, setRecording] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [audioError, setAudioError] = useState('');
|
||||
const playbackRef = useRef<{ player: HTMLAudioElement; url: string } | null>(null);
|
||||
|
||||
function stopPlayback() {
|
||||
const current = playbackRef.current;
|
||||
if (!current) return;
|
||||
current.player.pause();
|
||||
URL.revokeObjectURL(current.url);
|
||||
playbackRef.current = null;
|
||||
}
|
||||
|
||||
useEffect(() => () => stopPlayback(), []);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
fetchCourseModules().then(async ({ modules }) => {
|
||||
if (modules.length === 0) { if (active) setLoaded(true); return; }
|
||||
const loaded = await fetchCourseModule(modules[0].id);
|
||||
if (active) { setDetail(loaded); setSelectedId(loaded.tasks.find((task) => !task.attempted)?.id ?? loaded.tasks[0]?.id ?? ''); setLoaded(true); }
|
||||
const practice = await fetchCoursePractice(loaded.module.id);
|
||||
if (active) setPracticeTasks(practice.tasks);
|
||||
}).catch((err) => { if (active) { setError(err instanceof Error ? err.message : 'Kurs konnte nicht geladen werden.'); setLoaded(true); } }).finally(() => { if (active) setPracticeLoading(false); });
|
||||
return () => { active = false; };
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!recorded) { setRecordedUrl(''); return; }
|
||||
const url = URL.createObjectURL(recorded);
|
||||
setRecordedUrl(url);
|
||||
return () => URL.revokeObjectURL(url);
|
||||
}, [recorded]);
|
||||
|
||||
async function refresh() {
|
||||
if (!detail) return;
|
||||
const [core, practice] = await Promise.all([
|
||||
fetchCourseModule(detail.module.id), fetchCoursePractice(detail.module.id)
|
||||
]);
|
||||
setDetail(core);
|
||||
setPracticeTasks(practice.tasks);
|
||||
setPracticeTask((current) => current
|
||||
? practice.tasks.find((item) => item.id === current.id) ?? core.tasks.find((item) => item.id === current.id) ?? current
|
||||
: null);
|
||||
}
|
||||
|
||||
function selectTask(task: CourseTask, additional = false) {
|
||||
if (recording || busy) return;
|
||||
stopPlayback();
|
||||
setPracticeTask(additional ? task : null);
|
||||
setPracticeNotice('');
|
||||
setPracticeError('');
|
||||
setSelectedId(task.id);
|
||||
setAnswer(''); setResult(null); setPronResult(null); setRecorded(null); setError(''); setAudioError('');
|
||||
}
|
||||
|
||||
async function generatePractice() {
|
||||
if (!detail || busy || recording || practiceLoading) return;
|
||||
stopPlayback();
|
||||
setBusy(true); setGenerating(true); setError(''); setPracticeError(''); setPracticeNotice('');
|
||||
// Reuse this ID after a network error so retries cannot create duplicates.
|
||||
try {
|
||||
// randomUUID is unavailable on some browsers and HTTP origins.
|
||||
// The API accepts a 32-character random ID; getRandomValues also works
|
||||
// outside secure contexts. Keep the ID for retries after network errors.
|
||||
requestIdRef.current ??= Array.from(crypto.getRandomValues(new Uint8Array(16)),
|
||||
(value) => value.toString(16).padStart(2, '0')).join('');
|
||||
const response = await nextCoursePractice(detail.module.id, requestIdRef.current);
|
||||
requestIdRef.current = null;
|
||||
const receivedTask = { ...response.task, source: response.source };
|
||||
setPracticeTask(receivedTask);
|
||||
setSelectedId(response.task.id);
|
||||
setAnswer(''); setResult(null); setPronResult(null); setRecorded(null); setAudioError('');
|
||||
if ((response.source === 'flowise' || response.source === 'ai' || response.source === 'curated')) {
|
||||
setPracticeTasks((current) => [receivedTask, ...current.filter((item) => item.id !== response.task.id)].slice(0, 50));
|
||||
setPracticeNotice(response.source === 'curated' ? 'Eine Aufgabe aus dem geprüften Bestand ist bereit.' : 'Eine mit KI erstellte Zusatzaufgabe ist bereit.');
|
||||
} else {
|
||||
setPracticeNotice('Du erhältst eine feste Kursaufgabe zur Wiederholung.');
|
||||
}
|
||||
requestAnimationFrame(() => {
|
||||
exerciseRef.current?.focus({ preventScroll: true });
|
||||
exerciseRef.current?.scrollIntoView({ block: 'start', behavior: 'smooth' });
|
||||
});
|
||||
} catch (err) {
|
||||
setPracticeError(err instanceof Error ? err.message : 'Zusatzaufgabe konnte nicht geladen werden.');
|
||||
} finally { setBusy(false); setGenerating(false); }
|
||||
}
|
||||
|
||||
async function playAudio(task: CourseTask) {
|
||||
setAudioError('');
|
||||
setBusy(true);
|
||||
try {
|
||||
stopPlayback();
|
||||
const blob = task.skill === 'listening'
|
||||
? await fetchCourseAudio(task.id)
|
||||
: await fetchExerciseAudio(task.pronunciation_exercise!.id);
|
||||
const url = URL.createObjectURL(blob);
|
||||
const player = new Audio(url);
|
||||
playbackRef.current = { player, url };
|
||||
player.onended = () => { if (playbackRef.current?.player === player) stopPlayback(); };
|
||||
player.onerror = () => { if (playbackRef.current?.player === player) stopPlayback(); setAudioError('Audio konnte nicht abgespielt werden.'); };
|
||||
await player.play();
|
||||
} catch { stopPlayback(); setAudioError('Audio konnte nicht abgespielt werden. Bitte erneut versuchen.'); }
|
||||
finally { setBusy(false); }
|
||||
}
|
||||
|
||||
async function submit(task: CourseTask) {
|
||||
if (!answer.trim() || busy) return;
|
||||
setBusy(true); setError('');
|
||||
try {
|
||||
const response = await submitCourseAnswer(task.id, answer);
|
||||
setResult(response);
|
||||
await refresh();
|
||||
} catch (err) { setError(err instanceof Error ? err.message : 'Antwort konnte nicht bewertet werden.'); }
|
||||
finally { setBusy(false); }
|
||||
}
|
||||
|
||||
async function assess(task: CourseTask) {
|
||||
if (!recorded || !task.pronunciation_exercise || busy) return;
|
||||
setBusy(true); setError('');
|
||||
try {
|
||||
const response = await submitAttempt(task.pronunciation_exercise.id, recorded);
|
||||
setPronResult(response);
|
||||
setRecorded(null);
|
||||
await refresh();
|
||||
} catch (err) { setError(err instanceof Error ? err.message : 'Aussprache konnte nicht bewertet werden.'); }
|
||||
finally { setBusy(false); }
|
||||
}
|
||||
|
||||
if (error && !detail) return <p className="form-error">{error}</p>;
|
||||
if (loaded && !detail) return <p className="muted">Für deine aktuelle Sprache und Lernstufe ist noch kein Kursmodul verfügbar.</p>;
|
||||
if (!detail) return <p className="muted">Lade A1-Kurs...</p>;
|
||||
const task = practiceTask ?? detail.tasks.find((item) => item.id === selectedId);
|
||||
const skills = Object.entries(skillNames) as [CourseTask['skill'], string][];
|
||||
|
||||
return (
|
||||
<div className="view-stack">
|
||||
<header className="view-header">
|
||||
<div><p className="eyebrow">Geführter A1-Kurs</p><h1>{detail.module.title}</h1><p className="muted">{detail.module.description}</p></div>
|
||||
</header>
|
||||
<section className="panel course-progress" aria-label="Modulfortschritt">
|
||||
<strong>{detail.module.attempted_count} von {detail.module.task_count} Aufgaben bearbeitet</strong>
|
||||
<p className="muted">{detail.module.correct_count} Aufgaben richtig gelöst. „Bearbeitet“ bedeutet nicht „A1 bestanden“.</p>
|
||||
<progress max={detail.module.task_count || 1} value={detail.module.attempted_count} />
|
||||
</section>
|
||||
<section className="panel course-additional" aria-label="Zusätzlich üben">
|
||||
<div><h2>Zusätzlich üben</h2><p className="muted">Wortschatz und Grammatik wiederholen. Dein Fortschritt im festen Kurs bleibt davon getrennt.</p></div>
|
||||
<button type="button" className="primary-button" disabled={busy || recording || practiceLoading} onClick={() => void generatePractice()}>
|
||||
{generating ? 'Aufgabe wird vorbereitet…' : 'Neue Zusatzaufgabe'}
|
||||
</button>
|
||||
{practiceLoading && <p className="course-practice-status muted" role="status">Zusatzaufgaben werden geladen…</p>}
|
||||
{generating && <p className="course-practice-status muted" role="status">Eine passende Aufgabe wird vorbereitet. Das kann bis zu 25 Sekunden dauern.</p>}
|
||||
{practiceError && <p className="course-practice-status form-error" role="alert">Zusatzaufgabe konnte nicht geladen werden: {practiceError}</p>}
|
||||
{practiceNotice && <p className="course-practice-status muted" role="status">{practiceNotice}</p>}
|
||||
</section>
|
||||
<div className="course-layout">
|
||||
<nav className="panel course-task-list" aria-label="Kursaufgaben">
|
||||
{practiceTasks.length > 0 && <div className="course-skill-group">
|
||||
<h2>Deine Zusatzaufgaben</h2>
|
||||
{practiceTasks.map((item, index) => <button key={item.id} type="button" disabled={busy || recording}
|
||||
className={practiceTask?.id === item.id ? 'course-task active' : 'course-task'} onClick={() => selectTask(item, true)}>
|
||||
<span>{skillNames[item.skill]} · {index + 1}</span><span>{item.correct ? '✓' : item.attempted ? '↻' : '○'}</span>
|
||||
</button>)}
|
||||
</div>}
|
||||
{skills.map(([skill, name]) => {
|
||||
const tasks = detail.tasks.filter((item) => item.skill === skill);
|
||||
return tasks.length > 0 && <div key={skill} className="course-skill-group">
|
||||
<h2>{name} <small>{tasks.filter((item) => item.attempted).length}/{tasks.length} bearbeitet · {tasks.filter((item) => item.correct).length} Ziel erreicht</small></h2>
|
||||
{tasks.map((item, index) => <button key={item.id} type="button" disabled={recording || busy}
|
||||
className={!practiceTask && item.id === selectedId ? 'course-task active' : 'course-task'} onClick={() => selectTask(item)}>
|
||||
<span>Aufgabe {index + 1}</span><span>{item.correct ? '✓' : item.attempted ? '↻' : '○'}</span>
|
||||
</button>)}
|
||||
</div>;
|
||||
})}
|
||||
</nav>
|
||||
<section ref={exerciseRef} tabIndex={-1} className="panel course-exercise" aria-live="polite" aria-label="Aktuelle Kursaufgabe">
|
||||
{task && <>
|
||||
<p className="eyebrow">{practiceTask ? (practiceTask.source === 'curated' ? 'Aus geprüftem Aufgabenbestand · ' : practiceTask.source === 'ai' ? 'Mit KI erstellt · ' : practiceTask.source === 'flowise' ? 'Mit Flowise erstellt · ' : practiceTask.source === 'seed' ? 'Feste Kursaufgabe zur Wiederholung · ' : 'Zusätzlich üben · ') : ''}{skillNames[task.skill]}</p>
|
||||
<h2>{task.prompt}</h2>
|
||||
{task.passage && <p className="course-passage">{task.passage}</p>}
|
||||
{task.skill === 'listening' && <p className="muted">Höre zuerst zu. Der gesprochene Text erscheint nach deiner Antwort.</p>}
|
||||
{(task.skill === 'listening' || task.skill === 'pronunciation') && <button type="button" className="ghost-button" disabled={busy || recording}
|
||||
onClick={() => void playAudio(task)}>Anhören</button>}
|
||||
{audioError && <p className="form-error">{audioError}</p>}
|
||||
{task.kind === 'choice' && <div className="course-options" role="group" aria-label="Antwortmöglichkeiten">
|
||||
{(task.options ?? []).map((option) => <label key={option} className="course-option">
|
||||
<input type="radio" name={`answer-${task.id}`} value={option} checked={answer === option} onChange={() => setAnswer(option)} disabled={busy} /> {option}
|
||||
</label>)}
|
||||
</div>}
|
||||
{task.kind === 'short_text' && <label>Deine Antwort
|
||||
<input type="text" maxLength={200} value={answer} onChange={(event) => setAnswer(event.target.value)} disabled={busy} autoComplete="off" />
|
||||
</label>}
|
||||
{task.kind !== 'pronunciation' && <button type="button" className="primary-button" disabled={busy || !answer.trim()} onClick={() => void submit(task)}>
|
||||
{busy ? 'Wird geprüft...' : 'Antwort prüfen'}
|
||||
</button>}
|
||||
{task.kind === 'pronunciation' && task.pronunciation_exercise && <div className="course-pronunciation">
|
||||
<p className="target-text">{task.pronunciation_exercise.target_text}</p>
|
||||
<div className="action-row"><AudioRecorder key={task.id} onRecorded={setRecorded} onRecordingChange={setRecording}
|
||||
onRecordingStart={() => { setRecorded(null); setPronResult(null); }} disabled={busy} buttonLabel={recorded ? 'Erneut aufnehmen' : 'Aufnehmen'} secondary={Boolean(recorded)} />
|
||||
{recorded && !recording && <button type="button" className="primary-button" disabled={busy} onClick={() => void assess(task)}>Bewerten</button>}</div>
|
||||
{recordedUrl && !recording && <div className="recording-preview"><p className="muted">Du kannst die Aufnahme vor dem Bewerten anhören oder erneut aufnehmen.</p><audio controls src={recordedUrl} /></div>}
|
||||
{pronResult && <div className="course-feedback"><strong>Aussprache: {Math.round(pronResult.attempt.overall_score)} / 100</strong><p>{pronResult.teacher.teacher_feedback}</p></div>}
|
||||
</div>}
|
||||
{result?.task_id === task.id && <div className={result.correct ? 'course-feedback correct' : 'course-feedback'} role="status">
|
||||
<strong>{result.correct ? 'Richtig!' : 'Noch nicht richtig.'}</strong>
|
||||
<p>{result.explanation}</p><p>Musterantwort: {result.solution}</p>
|
||||
{result.transcript && <p>Gehörter Text: {result.transcript}</p>}
|
||||
</div>}
|
||||
|
||||
</>}
|
||||
{error && <p className="form-error" role="alert">{error}</p>}
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -162,6 +162,7 @@ export function PracticePage({ initialSelection }: Props) {
|
||||
|
||||
<section className="panel practice-panel">
|
||||
<p className="muted">{exercise.prompt_text}</p>
|
||||
{exercise.training_reason&&<p className="muted" role="note">Warum diese Übung: {exercise.training_reason}</p>}
|
||||
<PronunciationText targetText={exercise.target_text} words={result?.attempt.word_scores} />
|
||||
<div className="action-row">
|
||||
<button className="ghost-button" type="button" disabled={loadingNext || audioLoadingKey !== null || recording} onClick={() => void playReference('normal')}>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { fetchProgress } from '../api/lessons';
|
||||
import type { ProgressSummary } from '../api/types';
|
||||
import { PronunciationOverview } from '../components/PronunciationOverview';
|
||||
import { ScoreBadge } from '../components/ScoreBadge';
|
||||
|
||||
export function ProgressPage() {
|
||||
@@ -18,14 +19,14 @@ export function ProgressPage() {
|
||||
<div className="view-stack">
|
||||
<header className="view-header">
|
||||
<div>
|
||||
<p className="eyebrow">A1 Englisch</p>
|
||||
<p className="eyebrow">Lernübersicht</p>
|
||||
<h1>Fortschritt</h1>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section className="metric-grid">
|
||||
<div className="panel result-panel">
|
||||
<ScoreBadge label="Durchschnitt" value={progress.average_score} />
|
||||
<ScoreBadge label="Historischer Durchschnitt" value={progress.average_score} />
|
||||
</div>
|
||||
<div className="panel metric">
|
||||
<span>Versuche</span>
|
||||
@@ -33,35 +34,7 @@ export function ProgressPage() {
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="panel result-panel">
|
||||
<h2>Schwierige Woerter</h2>
|
||||
<div className="weak-list">
|
||||
{(progress.weak_words ?? []).length === 0 ? (
|
||||
<p className="muted">Noch keine Schwachstellen.</p>
|
||||
) : (
|
||||
(progress.weak_words ?? []).map((word) => (
|
||||
<span className={`word word-${word.highlight}`} key={word.word}>
|
||||
{word.word} {Math.round(word.accuracy)}
|
||||
</span>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="panel result-panel">
|
||||
<h2>Schwierige Laute</h2>
|
||||
<div className="weak-list">
|
||||
{(progress.weak_phonemes ?? []).length === 0 ? (
|
||||
<p className="muted">Noch keine bewerteten Lautschwächen.</p>
|
||||
) : (
|
||||
(progress.weak_phonemes ?? []).map((item) => (
|
||||
<span className="word word-weak" key={`${item.word}-${item.phoneme}`}>
|
||||
{item.word}: /{item.phoneme}/ {Math.round(item.accuracy)}
|
||||
</span>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
<PronunciationOverview />
|
||||
|
||||
<section className="panel result-panel">
|
||||
<h2>Letzte Versuche</h2>
|
||||
|
||||
Reference in New Issue
Block a user