Phonembewertung speichern und anzeigen
Azure-Phonemwerte in Versuchen sichern, schwache Laute im Fortschritt und Flowise-Kontext auswerten und die Web-Anzeige ergänzen. README dokumentiert Datenfluss, Betrieb und Grenzen der Funktion.
This commit is contained in:
@@ -1,20 +1,134 @@
|
||||
# Speech Learning App
|
||||
|
||||
Docker-basierter MVP fuer eine A1-Englisch-Lern-Web-App. Der Kern ist eine Go API, das Frontend ist React/TypeScript, FlowiseAI laeuft als eigener Container auf demselben VPS, und Azure Speech wird serverseitig gekapselt.
|
||||
Sprachlern-App für Ausspracheübungen auf A1-Niveau. Die Web-App nimmt Sprache auf und zeigt Übungen sowie Bewertungen an. Die Go-API steuert den Ablauf, speichert den Lernverlauf in PostgreSQL, lässt Flowise neue Übungen erzeugen und ruft Azure Speech zur Aussprachebewertung auf.
|
||||
|
||||
## Aktueller Funktionsumfang
|
||||
|
||||
- Registrierung, Login und Lernerprofil mit Zielsprache, Oberflächensprache und Tagesziel
|
||||
- Kurze englische `repeat_sentence`-Übungen aus Flowise; Seed-Übungen als Fallback
|
||||
- Audioaufnahme im Browser und Aussprachebewertung über Azure Speech
|
||||
- Gesamt-, Wort- und bei echten Azure-Antworten auch Phonemwerte
|
||||
- Feedback zum Versuch sowie Fortschrittsansicht mit schwachen Wörtern und Lauten
|
||||
- Mock-Modus für lokale Entwicklung ohne Azure-Zugang
|
||||
|
||||
Weitere Übungstypen, ein `evaluate_attempt`-Flowise-Task und ein langfristiges Fähigkeitsmodell pro Wort sind noch nicht implementiert.
|
||||
|
||||
## Architektur und Datenfluss
|
||||
|
||||
```text
|
||||
Browser/Web-App ──► Go-API ──► Flowise (nächste Übung)
|
||||
│
|
||||
├──────► Azure Speech (Aussprachebewertung, TTS)
|
||||
├──────► PostgreSQL (Profile, Übungen, Versuche)
|
||||
└──────► Redis
|
||||
```
|
||||
|
||||
Der Browser spricht nur mit der Go-API. API-Schlüssel für Flowise und Azure bleiben serverseitig. Die Go-API authentifiziert Nutzer, prüft Flowise-Antworten und entscheidet, was dauerhaft gespeichert wird. PostgreSQL ist die verbindliche Quelle für Übungen und Lernverlauf. Flowise erzeugt didaktisch passende Aufgaben, ändert aber keinen Lernstatus in PostgreSQL.
|
||||
|
||||
Eine Übungsrunde läuft so ab:
|
||||
|
||||
1. Die Web-App lädt das Dashboard oder fordert über `POST /lessons/next` eine neue Übung an.
|
||||
2. Die Go-API liest Profil und letzte Versuche aus PostgreSQL. Sie erstellt daraus einen kompakten Kontext und sendet `task: "next_exercise"` an Flowise.
|
||||
3. Die Go-API prüft die erzeugte `repeat_sentence`-Übung und speichert sie. Falls Flowise ausfällt oder keine gültige Übung liefert, verwendet die API eine Seed-Übung.
|
||||
4. Die Web-App zeigt den Satz, nimmt Sprache auf und sendet Audio und `exercise_id` an `POST /practice/attempts`.
|
||||
5. Die Go-API schickt das Audio mit dem Referenzsatz an Azure Speech, verarbeitet die Bewertung und speichert den Versuch in PostgreSQL.
|
||||
6. Die Web-App zeigt Ergebnis und Lehrerfeedback. `GET /progress` liefert die letzten Versuche sowie daraus berechnete schwache Wörter und Laute.
|
||||
|
||||
Flowise wird bei der **unmittelbaren Bewertung** eines Versuchs derzeit nicht aufgerufen. Das Lehrerfeedback entsteht in der Go-API anhand der Azure-Werte. Insbesondere entscheidet Flowise weder über „gemeistert“ noch über einen Niveauwechsel.
|
||||
|
||||
## Aussprachebewertung auf Phonemebene
|
||||
|
||||
Die Go-API fordert Azure Pronunciation Assessment mit `Granularity: "Phoneme"`, `GradingSystem: "HundredMark"` und `PhonemeAlphabet: "IPA"` an. Azure kann dabei neben Satz- und Wortwerten auch Genauigkeitswerte für einzelne Laute liefern. Die API übernimmt nur tatsächlich vorhandene Phonemwerte; ein fehlender Wert wird nicht als `0` interpretiert. Ein echter Wert `0` bleibt dagegen erhalten.
|
||||
|
||||
Ein vereinfachter Ausschnitt aus einem gespeicherten Versuch und der Antwort von `POST /practice/attempts`:
|
||||
|
||||
```json
|
||||
{
|
||||
"word_scores": [
|
||||
{
|
||||
"word": "water",
|
||||
"accuracy": 72,
|
||||
"phonemes": ["w", "ɔ", "t", "ə"],
|
||||
"phoneme_scores": [
|
||||
{ "phoneme": "w", "accuracy": 91, "highlight": "good" },
|
||||
{ "phoneme": "t", "accuracy": 58, "highlight": "weak" }
|
||||
],
|
||||
"highlight": "weak"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
`phonemes` enthält die von Azure gelieferten Lautbezeichnungen. `phoneme_scores` enthält nur Laute, für die Azure auch einen Genauigkeitswert geliefert hat. Die Beispielzahlen oben sind illustrativ und keine erwarteten Werte für „water“.
|
||||
|
||||
Die Einstufung in der aktuellen App ist eine einfache Anzeigeregel: unter `75` = `weak`, `75` bis unter `85` = `ok`, ab `85` = `good`. Das ist keine Aussage darüber, welcher konkrete Artikulationsfehler vorlag. Die Lautanalyse nach einem Versuch zeigt die bewerteten Laute pro Wort. Bei einem gemessenen schwachen Laut kann das Lehrerfeedback das Wort, das Phonem und dessen Punktzahl nennen; bei sehr hohen Satzwerten empfiehlt es eine neue Übung.
|
||||
|
||||
PostgreSQL speichert `phoneme_scores` als Teil des bestehenden `attempts.word_scores_json`-Felds. Dafür ist keine neue Tabelle und keine Migration nötig. Alte Versuche enthalten diese Werte nicht rückwirkend. Der Mock-Modus liefert derzeit nur Wortwerte; dort zeigt die Web-App entsprechend an, dass keine Lautwerte verfügbar sind.
|
||||
|
||||
### Schwache Laute im Fortschritt
|
||||
|
||||
`GET /progress` enthält zusätzlich `weak_phonemes`. Die Go-API berechnet diese Liste aus den letzten **20** Versuchen; bei der nächsten Übung betrachtet sie die letzten **10**. Pro Kombination aus Wort und Laut zählt der neueste bewertete Versuch. Wird derselbe Laut in diesem Versuch mehrfach bewertet, zählt der niedrigste Wert. Ein neuerer guter Wert entfernt damit eine ältere Schwäche aus dem betrachteten Fenster. Ausgelassene Wörter (`Omission`) werden für die Lautliste übersprungen. Die Liste ist nach niedrigstem Wert sortiert und auf 12 Einträge begrenzt.
|
||||
|
||||
```json
|
||||
{
|
||||
"weak_phonemes": [
|
||||
{ "word": "water", "phoneme": "t", "accuracy": 58 }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Das ist eine **Momentaufnahme aus den letzten Versuchen**, keine dauerhafte Diagnose oder ein über alle Zeiten berechneter Beherrschungsgrad. Schwache Wörter werden unabhängig davon ebenfalls aus dem jüngsten Wortwert im betrachteten Fenster berechnet.
|
||||
|
||||
## Flowise-Anbindung
|
||||
|
||||
Die Go-API ruft `POST /api/v1/prediction/{FLOWISE_CHATFLOW_ID}` auf. Das Feld `question` enthält den Lernkontext als JSON-String; `overrideConfig.sessionId` ordnet die Anfrage der Übungssitzung zu. Der derzeit unterstützte Task heißt `next_exercise`.
|
||||
|
||||
Zum Kontext gehören unter anderem `profile`, `progress`, `recent_weak_words`, `recent_weak_phonemes`, `preferred_type` und die zuletzt benutzten Sätze unter `avoid_reference_texts`. Einzelne rohe `phoneme_scores` aus allen jüngsten Versuchen werden vor dem Flowise-Aufruf entfernt; die kompakte Liste `recent_weak_phonemes` transportiert den relevanten Lautfokus. Flowise soll einen anderen Satz als die zuletzt verwendeten erzeugen, kann aber dasselbe Zielwort erneut üben.
|
||||
|
||||
Der Flowise-Flow braucht weiterhin einen Learning Planner und einen Exercise Generator. In der bestehenden Flowise-Oberfläche ist die Eingabe als `{{question}}` verfügbar. Ergänze im **Planner-Prompt** sinngemäß diese Regel:
|
||||
|
||||
```text
|
||||
Lies recent_weak_phonemes aus dem Eingabe-JSON. Wenn dort gemessene niedrige Werte stehen, darfst du das zugehörige Wort für eine Ausspracheübung wählen. Nenne einen konkreten Laut nur, wenn er mit Messwert übergeben wurde. Ein niedriger Wortwert allein belegt keinen bestimmten Lautfehler. Erfinde keine Lautprobleme, Trends oder abgeschlossenen Lernstufen.
|
||||
```
|
||||
|
||||
Der **Generator** soll das vom Planner gewählte Zielwort in einen kurzen natürlichen A1-Satz aufnehmen. `focus_points` dürfen einen konkreten Laut nur nennen, wenn der Planner ihn aus einem gemessenen `recent_weak_phonemes`-Eintrag übernommen hat. Das Antwortschema bleibt unverändert:
|
||||
|
||||
```json
|
||||
{
|
||||
"exercise_type": "repeat_sentence",
|
||||
"target_language": "en-US",
|
||||
"cefr_level": "A1",
|
||||
"reference_text": "I drink water every day.",
|
||||
"display_prompt": "Sprich den Satz nach. Achte besonders auf water.",
|
||||
"tts_text": "I drink water every day.",
|
||||
"focus_points": ["water"],
|
||||
"success_criteria": ["Sprich den vollständigen Satz gut verständlich nach."],
|
||||
"reason_for_choice": "Water wurde in den übergebenen Daten als schwierig bewertet."
|
||||
}
|
||||
```
|
||||
|
||||
Die Go-API validiert die Antwort und vergibt selbst die Übungs-ID. Die Flowise-Prompts werden in der Flowise-Oberfläche verwaltet; eine Änderung am Go-Code aktualisiert die dort gespeicherten Prompts nicht automatisch. Weitere Hinweise stehen in [flowise/README.md](flowise/README.md) und [flowise/agentflow-v2-setup.md](flowise/agentflow-v2-setup.md).
|
||||
|
||||
## Start auf dem VPS
|
||||
|
||||
Die Standard-Compose-Datei ist für den VPS vorgesehen. `speech-web` und `speech-api` hängen am vorhandenen Docker-Netzwerk `web`; die Datenbank liegt auf einem persistenten Docker-Volume.
|
||||
|
||||
```bash
|
||||
docker compose up --build
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
Danach:
|
||||
|
||||
- Web-App: https://speech.v2202510301049387828.goodsrv.de
|
||||
- API Healthcheck: https://speech.v2202510301049387828.goodsrv.de/api/health
|
||||
- Flowise: vorhandene Instanz ueber `FLOWISE_BASE_URL`
|
||||
- API-Healthcheck: https://speech.v2202510301049387828.goodsrv.de/api/health
|
||||
- Flowise: vorhandene Instanz über `FLOWISE_BASE_URL`
|
||||
|
||||
Der Default-Compose ist fuer den VPS portlos und haengt `speech-web`/`speech-api` an das bestehende Docker-Netzwerk `web`.
|
||||
Nach einem Git-Update, das API und Web-App ändert, die beiden Dienste neu bauen:
|
||||
|
||||
```bash
|
||||
git pull
|
||||
docker compose up -d --build speech-api speech-web
|
||||
```
|
||||
|
||||
Für echte Phonemwerte müssen in `.env` `AZURE_SPEECH_KEY` und `AZURE_SPEECH_REGION` gesetzt sein sowie `AZURE_ENABLE_MOCK=false`. Fehlt ein Azure-Schlüssel oder die Region, schaltet die API auch bei deaktiviertem Mock-Schalter auf Mock-Bewertung um. Für Flowise müssen `FLOWISE_BASE_URL` und `FLOWISE_CHATFLOW_ID` auf den verwendeten Flow zeigen.
|
||||
|
||||
## Lokale Entwicklung
|
||||
|
||||
@@ -23,49 +137,45 @@ cp .env.example .env
|
||||
docker compose -f docker-compose.dev.yml up --build
|
||||
```
|
||||
|
||||
Danach:
|
||||
|
||||
- Web-App: http://localhost:5173
|
||||
- API Healthcheck: http://localhost:8080/health
|
||||
- API-Healthcheck: http://localhost:8080/health
|
||||
- Flowise: http://localhost:3000
|
||||
|
||||
Mit `AZURE_ENABLE_MOCK=true` laeuft die Aussprachebewertung ohne Azure Credentials. Fuer echte Azure Speech Calls `AZURE_SPEECH_KEY`, `AZURE_SPEECH_REGION` setzen und `AZURE_ENABLE_MOCK=false` verwenden.
|
||||
Mit `AZURE_ENABLE_MOCK=true` funktioniert die Wortbewertung ohne Azure-Zugang; Lautwerte gibt es dann nicht. Für echte Bewertungen Azure-Zugangsdaten setzen und `AZURE_ENABLE_MOCK=false` verwenden.
|
||||
|
||||
## Prüfung nach dem Deployment
|
||||
|
||||
1. Einloggen und eine neue Übung öffnen. In den API-Logs sollte für eine von Flowise angenommene Übung `source: "flowise"` erscheinen; bei einem Fehler wird eine Seed-Übung verwendet.
|
||||
2. Den Satz aufnehmen. Nach dem Absenden sollten Gesamt- und Wortwerte sowie unter **Lautanalyse** bewertete IPA-Laute erscheinen.
|
||||
3. **Fortschritt** öffnen. Ein Laut unter `75` sollte unter **Schwierige Laute** auftauchen. Nach einer neueren guten Bewertung desselben Lauts im selben Wort sollte er dort verschwinden, sofern er noch im betrachteten Versuchsfenster liegt.
|
||||
4. Wenn **Lautanalyse** „keine Lautwerte verfügbar“ zeigt, zunächst Azure-Konfiguration und `provider` in der Antwort von `POST /practice/attempts` prüfen. `provider: "mock"` hat keine Phonemwerte. Auch echte Azure-Antworten können für einzelne Laute keinen Wert liefern.
|
||||
|
||||
API-Logs auf dem VPS:
|
||||
|
||||
```bash
|
||||
docker compose logs --since=10m speech-api
|
||||
```
|
||||
|
||||
Tests und Web-Build im Quellverzeichnis:
|
||||
|
||||
```bash
|
||||
cd apps/api && go test ./...
|
||||
cd ../web && npm run build
|
||||
```
|
||||
|
||||
## Debug
|
||||
|
||||
Debug ist ueber `.env` aktivierbar:
|
||||
Debug-Endpunkte und der Navigationspunkt **Debug** lassen sich über `.env` aktivieren:
|
||||
|
||||
```env
|
||||
DEBUG_ENABLED=true
|
||||
LOG_LEVEL=debug
|
||||
```
|
||||
|
||||
Danach:
|
||||
Danach die API neu erstellen:
|
||||
|
||||
```bash
|
||||
docker compose up -d --force-recreate speech-api
|
||||
```
|
||||
|
||||
Eingeloggte Nutzer sehen dann in der Web-App den Navigationspunkt `Debug`. Die Ausgaben sind maskiert und zeigen keine Secrets.
|
||||
|
||||
## MVP-Funktionen
|
||||
|
||||
- Registrierung und Login
|
||||
- A1-Lernerprofil mit `en-US`
|
||||
- Dashboard mit Tagesziel und naechster Uebung
|
||||
- Browser-Audioaufnahme
|
||||
- Pronunciation Assessment API mit Azure/Mock-Fallback
|
||||
- Visuelles Wort-Feedback
|
||||
- Flowise-Adapter mit Mock-Fallback
|
||||
- Datenmodell vorbereitet fuer weitere Zielsprachen
|
||||
|
||||
## Architektur
|
||||
|
||||
```txt
|
||||
web -> api -> postgres
|
||||
-> redis
|
||||
-> flowise
|
||||
-> azure speech
|
||||
```
|
||||
|
||||
Der Browser spricht nur mit der Go API. Azure- und Flowise-Secrets bleiben im Backend.
|
||||
Die Debug-Ausgaben sind maskiert und geben keine Zugangsschlüssel aus.
|
||||
|
||||
@@ -49,11 +49,24 @@ type Exercise struct {
|
||||
}
|
||||
|
||||
type WordScore struct {
|
||||
Word string `json:"word"`
|
||||
Accuracy float64 `json:"accuracy"`
|
||||
ErrorType string `json:"error_type,omitempty"`
|
||||
Phonemes []string `json:"phonemes,omitempty"`
|
||||
Highlight string `json:"highlight"`
|
||||
Word string `json:"word"`
|
||||
Accuracy float64 `json:"accuracy"`
|
||||
ErrorType string `json:"error_type,omitempty"`
|
||||
Phonemes []string `json:"phonemes,omitempty"`
|
||||
PhonemeScores []PhonemeScore `json:"phoneme_scores,omitempty"`
|
||||
Highlight string `json:"highlight"`
|
||||
}
|
||||
|
||||
type PhonemeScore struct {
|
||||
Phoneme string `json:"phoneme"`
|
||||
Accuracy float64 `json:"accuracy"`
|
||||
Highlight string `json:"highlight"`
|
||||
}
|
||||
|
||||
type WeakPhoneme struct {
|
||||
Word string `json:"word"`
|
||||
Phoneme string `json:"phoneme"`
|
||||
Accuracy float64 `json:"accuracy"`
|
||||
}
|
||||
|
||||
type PronunciationResult struct {
|
||||
@@ -84,11 +97,12 @@ type Attempt struct {
|
||||
}
|
||||
|
||||
type ProgressSummary struct {
|
||||
TotalAttempts int `json:"total_attempts"`
|
||||
AverageScore float64 `json:"average_score"`
|
||||
WeakWords []WordScore `json:"weak_words"`
|
||||
RecentAttempts []Attempt `json:"recent_attempts"`
|
||||
DailyGoalMinutes int `json:"daily_goal_minutes"`
|
||||
TotalAttempts int `json:"total_attempts"`
|
||||
AverageScore float64 `json:"average_score"`
|
||||
WeakWords []WordScore `json:"weak_words"`
|
||||
WeakPhonemes []WeakPhoneme `json:"weak_phonemes"`
|
||||
RecentAttempts []Attempt `json:"recent_attempts"`
|
||||
DailyGoalMinutes int `json:"daily_goal_minutes"`
|
||||
}
|
||||
|
||||
type GeneratedExerciseRequest struct {
|
||||
|
||||
@@ -54,6 +54,7 @@ func (f *FlowiseTeacher) NextExercise(ctx context.Context, input domain.Generate
|
||||
ReasonForChoice: "Fallback exercise because Flowise did not return a valid exercise.",
|
||||
Source: "fallback",
|
||||
}
|
||||
progress := compactProgressForFlowise(input.Progress)
|
||||
payload := map[string]any{
|
||||
"task": "next_exercise",
|
||||
"user_id": input.UserID,
|
||||
@@ -61,16 +62,37 @@ func (f *FlowiseTeacher) NextExercise(ctx context.Context, input domain.Generate
|
||||
"cefr_level": input.CEFRLevel,
|
||||
"ui_language": input.UILanguage,
|
||||
"profile": input.Profile,
|
||||
"progress": input.Progress,
|
||||
"recent_weak_words": input.RecentWeakWords,
|
||||
"progress": progress,
|
||||
"recent_weak_words": withoutPhonemeScores(input.RecentWeakWords),
|
||||
"recent_weak_phonemes": input.Progress.WeakPhonemes,
|
||||
"preferred_type": valueOr(input.PreferredType, "repeat_sentence"),
|
||||
"avoid_reference_text": input.AvoidReferenceText,
|
||||
"avoid_reference_texts": input.AvoidReferenceTexts,
|
||||
"rules": "Generate one A1 English pronunciation exercise. Return valid JSON only with fields: exercise_type, target_language, cefr_level, reference_text, display_prompt, tts_text, focus_points, success_criteria, reason_for_choice. The reference_text must differ from every sentence in avoid_reference_texts. The same target word may still be used.",
|
||||
"rules": "Generate one A1 English pronunciation exercise. Return valid JSON only with fields: exercise_type, target_language, cefr_level, reference_text, display_prompt, tts_text, focus_points, success_criteria, reason_for_choice. The reference_text must differ from every sentence in avoid_reference_texts. Use recent_weak_phonemes only when measured scores are provided; do not invent pronunciation errors.",
|
||||
}
|
||||
return f.askExercise(ctx, payload, input, fallback)
|
||||
}
|
||||
|
||||
func compactProgressForFlowise(progress domain.ProgressSummary) domain.ProgressSummary {
|
||||
progress.WeakWords = withoutPhonemeScores(progress.WeakWords)
|
||||
recent := make([]domain.Attempt, len(progress.RecentAttempts))
|
||||
for i, attempt := range progress.RecentAttempts {
|
||||
recent[i] = attempt
|
||||
recent[i].WordScores = withoutPhonemeScores(attempt.WordScores)
|
||||
}
|
||||
progress.RecentAttempts = recent
|
||||
return progress
|
||||
}
|
||||
|
||||
func withoutPhonemeScores(words []domain.WordScore) []domain.WordScore {
|
||||
clean := make([]domain.WordScore, len(words))
|
||||
copy(clean, words)
|
||||
for i := range clean {
|
||||
clean[i].PhonemeScores = nil
|
||||
}
|
||||
return clean
|
||||
}
|
||||
|
||||
func (f *FlowiseTeacher) FeedbackForAttempt(ctx context.Context, targetText string, result domain.PronunciationResult, weakWords []domain.WordScore) (domain.TeacherResponse, error) {
|
||||
_ = ctx
|
||||
_ = weakWords
|
||||
@@ -261,10 +283,22 @@ func parseGeneratedExerciseJSON(value json.RawMessage) (domain.GeneratedExercise
|
||||
|
||||
func mockFeedback(targetText string, result domain.PronunciationResult) domain.TeacherResponse {
|
||||
weakWord := ""
|
||||
weakPhoneme := domain.PhonemeScore{}
|
||||
weakPhonemeWord := ""
|
||||
for _, word := range result.WordScores {
|
||||
if word.Highlight == "weak" {
|
||||
weakWord = word.Word
|
||||
break
|
||||
if weakWord == "" {
|
||||
weakWord = word.Word
|
||||
}
|
||||
}
|
||||
if strings.EqualFold(word.ErrorType, "Omission") {
|
||||
continue
|
||||
}
|
||||
for _, phoneme := range word.PhonemeScores {
|
||||
if phoneme.Accuracy < 75 && (weakPhonemeWord == "" || phoneme.Accuracy < weakPhoneme.Accuracy) {
|
||||
weakPhoneme = phoneme
|
||||
weakPhonemeWord = word.Word
|
||||
}
|
||||
}
|
||||
}
|
||||
feedback := "Der Satz braucht noch etwas Übung. Sprich ihn noch einmal nach."
|
||||
@@ -273,6 +307,9 @@ func mockFeedback(targetText string, result domain.PronunciationResult) domain.T
|
||||
case result.OverallScore >= 95 && result.AccuracyScore >= 95 && result.FluencyScore >= 95 && result.CompletenessScore >= 95:
|
||||
feedback = "Ausgezeichnet gesprochen! Die Aussprache dieses Satzes wurde sehr hoch bewertet."
|
||||
nextRecommendation = "Du kannst mit einer neuen Übung weitermachen."
|
||||
case weakPhonemeWord != "":
|
||||
feedback = fmt.Sprintf("Im Wort %q wurde der Laut /%s/ mit %.0f von 100 Punkten bewertet.", weakPhonemeWord, weakPhoneme.Phoneme, weakPhoneme.Accuracy)
|
||||
nextRecommendation = fmt.Sprintf("Wiederhole den Satz und achte besonders auf %q.", weakPhonemeWord)
|
||||
case weakWord != "":
|
||||
feedback = fmt.Sprintf("Das Wort %q wurde noch unsicher bewertet. Übe es im Satz noch einmal.", weakWord)
|
||||
nextRecommendation = fmt.Sprintf("Wiederhole den Satz und achte besonders auf %q.", weakWord)
|
||||
|
||||
@@ -39,6 +39,20 @@ func TestFeedbackForWeakWordNamesObservedProblem(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeedbackNamesMeasuredWeakPhoneme(t *testing.T) {
|
||||
result := domain.PronunciationResult{
|
||||
OverallScore: 79,
|
||||
WordScores: []domain.WordScore{{
|
||||
Word: "water", Accuracy: 72, Highlight: "weak",
|
||||
PhonemeScores: []domain.PhonemeScore{{Phoneme: "w", Accuracy: 90}, {Phoneme: "t", Accuracy: 58}},
|
||||
}},
|
||||
}
|
||||
feedback := mockFeedback("I drink water.", result)
|
||||
if !strings.Contains(feedback.TeacherFeedback, "/t/") || !strings.Contains(feedback.TeacherFeedback, "58") {
|
||||
t.Fatalf("expected measured phoneme in feedback, got %#v", feedback)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlowiseNextExerciseSendsSessionAndParsesResponse(t *testing.T) {
|
||||
var requestBody map[string]json.RawMessage
|
||||
|
||||
@@ -78,7 +92,14 @@ func TestFlowiseNextExerciseSendsSessionAndParsesResponse(t *testing.T) {
|
||||
}, slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||
|
||||
exercise, err := teacher.NextExercise(context.Background(), domain.GeneratedExerciseRequest{
|
||||
UserID: "usr_1",
|
||||
UserID: "usr_1",
|
||||
Progress: domain.ProgressSummary{
|
||||
WeakPhonemes: []domain.WeakPhoneme{{Word: "water", Phoneme: "t", Accuracy: 58}},
|
||||
RecentAttempts: []domain.Attempt{{WordScores: []domain.WordScore{{
|
||||
Word: "water", Accuracy: 70, PhonemeScores: []domain.PhonemeScore{{Phoneme: "t", Accuracy: 58}},
|
||||
}}}},
|
||||
},
|
||||
RecentWeakWords: []domain.WordScore{{Word: "water", Accuracy: 70, PhonemeScores: []domain.PhonemeScore{{Phoneme: "t", Accuracy: 58}}}},
|
||||
TargetLanguage: "en-US",
|
||||
CEFRLevel: "A1",
|
||||
SessionID: "usr_1:en-US:practice",
|
||||
@@ -128,6 +149,12 @@ func TestFlowiseNextExerciseSendsSessionAndParsesResponse(t *testing.T) {
|
||||
if texts, ok := question["avoid_reference_texts"].([]any); !ok || len(texts) != 2 {
|
||||
t.Fatalf("unexpected avoid_reference_texts %#v", question["avoid_reference_texts"])
|
||||
}
|
||||
if phonemes, ok := question["recent_weak_phonemes"].([]any); !ok || len(phonemes) != 1 {
|
||||
t.Fatalf("weak phonemes were not sent to Flowise: %#v", question["recent_weak_phonemes"])
|
||||
}
|
||||
if strings.Contains(questionText, "phoneme_scores") {
|
||||
t.Fatal("raw phoneme scores should be summarized before sending progress to Flowise")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidGeneratedExerciseRejectsEarlierRecentSentence(t *testing.T) {
|
||||
|
||||
@@ -157,7 +157,11 @@ type azurePronunciationResponse struct {
|
||||
ErrorType string `json:"ErrorType"`
|
||||
} `json:"PronunciationAssessment"`
|
||||
Phonemes []struct {
|
||||
Phoneme string `json:"Phoneme"`
|
||||
Phoneme string `json:"Phoneme"`
|
||||
AccuracyScore *float64 `json:"AccuracyScore"`
|
||||
PronunciationAssessment struct {
|
||||
AccuracyScore *float64 `json:"AccuracyScore"`
|
||||
} `json:"PronunciationAssessment"`
|
||||
} `json:"Phonemes"`
|
||||
} `json:"Words"`
|
||||
} `json:"NBest"`
|
||||
@@ -183,18 +187,29 @@ func parseAzurePronunciation(body []byte) (domain.PronunciationResult, error) {
|
||||
}
|
||||
for _, word := range best.Words {
|
||||
phonemes := make([]string, 0, len(word.Phonemes))
|
||||
phonemeScores := make([]domain.PhonemeScore, 0, len(word.Phonemes))
|
||||
for _, phoneme := range word.Phonemes {
|
||||
if phoneme.Phoneme != "" {
|
||||
phonemes = append(phonemes, phoneme.Phoneme)
|
||||
accuracy := phoneme.PronunciationAssessment.AccuracyScore
|
||||
if accuracy == nil {
|
||||
accuracy = phoneme.AccuracyScore
|
||||
}
|
||||
if accuracy != nil {
|
||||
phonemeScores = append(phonemeScores, domain.PhonemeScore{
|
||||
Phoneme: phoneme.Phoneme, Accuracy: *accuracy, Highlight: highlightFor(*accuracy),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
score := firstScore(word.AccuracyScore, word.PronunciationAssessment.AccuracyScore)
|
||||
result.WordScores = append(result.WordScores, domain.WordScore{
|
||||
Word: word.Word,
|
||||
Accuracy: score,
|
||||
ErrorType: firstNonEmpty(word.PronunciationAssessment.ErrorType, word.ErrorType),
|
||||
Phonemes: phonemes,
|
||||
Highlight: highlightFor(score),
|
||||
Word: word.Word,
|
||||
Accuracy: score,
|
||||
ErrorType: firstNonEmpty(word.PronunciationAssessment.ErrorType, word.ErrorType),
|
||||
Phonemes: phonemes,
|
||||
PhonemeScores: phonemeScores,
|
||||
Highlight: highlightFor(score),
|
||||
})
|
||||
}
|
||||
return result, nil
|
||||
@@ -238,7 +253,7 @@ func highlightFor(score float64) string {
|
||||
switch {
|
||||
case score >= 85:
|
||||
return "good"
|
||||
case score >= 70:
|
||||
case score >= 75:
|
||||
return "ok"
|
||||
default:
|
||||
return "weak"
|
||||
|
||||
@@ -57,4 +57,38 @@ func TestParseAzurePronunciationTopLevelScores(t *testing.T) {
|
||||
if result.WordScores[0].Highlight != "good" {
|
||||
t.Fatalf("expected good highlight, got %s", result.WordScores[0].Highlight)
|
||||
}
|
||||
if len(result.WordScores[0].PhonemeScores) != 0 {
|
||||
t.Fatalf("unscored phonemes must not become zero-point weaknesses: %#v", result.WordScores[0].PhonemeScores)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseAzurePronunciationKeepsPhonemeScores(t *testing.T) {
|
||||
body := []byte(`{
|
||||
"NBest": [{"Display":"water","PronScore":82,"Words":[{
|
||||
"Word":"water","AccuracyScore":80,
|
||||
"Phonemes":[
|
||||
{"Phoneme":"w","PronunciationAssessment":{"AccuracyScore":93}},
|
||||
{"Phoneme":"ɔ","PronunciationAssessment":{"AccuracyScore":0}},
|
||||
{"Phoneme":"t","AccuracyScore":58},
|
||||
{"Phoneme":"ə"}
|
||||
]
|
||||
}]}]
|
||||
}`)
|
||||
result, err := parseAzurePronunciation(body)
|
||||
if err != nil {
|
||||
t.Fatalf("parse azure pronunciation: %v", err)
|
||||
}
|
||||
word := result.WordScores[0]
|
||||
if len(word.Phonemes) != 4 || len(word.PhonemeScores) != 3 {
|
||||
t.Fatalf("expected four phoneme labels and three scored phonemes, got %#v", word)
|
||||
}
|
||||
if word.PhonemeScores[0].Accuracy != 93 || word.PhonemeScores[0].Highlight != "good" {
|
||||
t.Fatalf("unexpected first phoneme score %#v", word.PhonemeScores[0])
|
||||
}
|
||||
if word.PhonemeScores[1].Accuracy != 0 || word.PhonemeScores[1].Highlight != "weak" {
|
||||
t.Fatalf("zero is a valid low score, got %#v", word.PhonemeScores[1])
|
||||
}
|
||||
if word.PhonemeScores[2].Accuracy != 58 || word.PhonemeScores[2].Highlight != "weak" {
|
||||
t.Fatalf("top-level phoneme score was not read: %#v", word.PhonemeScores[2])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"speech-learning-api/internal/domain"
|
||||
@@ -393,6 +394,7 @@ func (s *PostgresStore) Progress(ctx context.Context, userID string, limit int)
|
||||
return domain.ProgressSummary{}, err
|
||||
}
|
||||
summary.WeakWords = latestWeakWords(summary.RecentAttempts)
|
||||
summary.WeakPhonemes = latestWeakPhonemes(summary.RecentAttempts)
|
||||
return summary, nil
|
||||
}
|
||||
|
||||
@@ -416,6 +418,57 @@ func latestWeakWords(attempts []domain.Attempt) []domain.WordScore {
|
||||
return weak
|
||||
}
|
||||
|
||||
// Keep the newest scored occurrence for each word and phoneme. Within one
|
||||
// attempt, use the lowest score if the same sound occurs more than once.
|
||||
func latestWeakPhonemes(attempts []domain.Attempt) []domain.WeakPhoneme {
|
||||
seen := make(map[string]bool)
|
||||
var weak []domain.WeakPhoneme
|
||||
for _, attempt := range attempts {
|
||||
current := make(map[string]domain.WeakPhoneme)
|
||||
for _, word := range attempt.WordScores {
|
||||
if strings.EqualFold(word.ErrorType, "Omission") {
|
||||
continue
|
||||
}
|
||||
wordKey := strings.ToLower(strings.TrimSpace(word.Word))
|
||||
if wordKey == "" {
|
||||
continue
|
||||
}
|
||||
for _, phoneme := range word.PhonemeScores {
|
||||
name := strings.TrimSpace(phoneme.Phoneme)
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
key := wordKey + "\x00" + name
|
||||
if seen[key] {
|
||||
continue
|
||||
}
|
||||
if previous, ok := current[key]; !ok || phoneme.Accuracy < previous.Accuracy {
|
||||
current[key] = domain.WeakPhoneme{Word: word.Word, Phoneme: name, Accuracy: phoneme.Accuracy}
|
||||
}
|
||||
}
|
||||
}
|
||||
for key, score := range current {
|
||||
seen[key] = true
|
||||
if score.Accuracy < 75 {
|
||||
weak = append(weak, score)
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Slice(weak, func(i, j int) bool {
|
||||
if weak[i].Accuracy == weak[j].Accuracy {
|
||||
if weak[i].Word == weak[j].Word {
|
||||
return weak[i].Phoneme < weak[j].Phoneme
|
||||
}
|
||||
return weak[i].Word < weak[j].Word
|
||||
}
|
||||
return weak[i].Accuracy < weak[j].Accuracy
|
||||
})
|
||||
if len(weak) > 12 {
|
||||
weak = weak[:12]
|
||||
}
|
||||
return weak
|
||||
}
|
||||
|
||||
func (s *PostgresStore) CreateConversationSession(ctx context.Context, userID, targetLanguage, cefrLevel string) (domain.ConversationSession, error) {
|
||||
session := domain.ConversationSession{
|
||||
ID: NewID("con"),
|
||||
|
||||
@@ -23,3 +23,20 @@ func TestLatestWeakWordsUsesNewestScorePerWord(t *testing.T) {
|
||||
t.Fatalf("latest scores should clear water and keep coffee/please weak, got %#v", weak)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLatestWeakPhonemesUsesNewestScoredAttempt(t *testing.T) {
|
||||
attempts := []domain.Attempt{
|
||||
{WordScores: []domain.WordScore{
|
||||
{Word: "Water", PhonemeScores: []domain.PhonemeScore{{Phoneme: "w", Accuracy: 100}, {Phoneme: "t", Accuracy: 61}, {Phoneme: "t", Accuracy: 55}}},
|
||||
}},
|
||||
{WordScores: []domain.WordScore{
|
||||
{Word: "water", PhonemeScores: []domain.PhonemeScore{{Phoneme: "w", Accuracy: 42}, {Phoneme: "t", Accuracy: 95}}},
|
||||
{Word: "tea", PhonemeScores: []domain.PhonemeScore{{Phoneme: "iː", Accuracy: 68}}},
|
||||
{Word: "missed", ErrorType: "Omission", PhonemeScores: []domain.PhonemeScore{{Phoneme: "m", Accuracy: 0}}},
|
||||
}},
|
||||
}
|
||||
weak := latestWeakPhonemes(attempts)
|
||||
if len(weak) != 2 || weak[0].Phoneme != "t" || weak[0].Accuracy != 55 || weak[1].Word != "tea" {
|
||||
t.Fatalf("newer /w/ success should clear old weakness; latest /t/ and /iː/ should remain, got %#v", weak)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,9 +38,22 @@ export type WordScore = {
|
||||
accuracy: number;
|
||||
error_type?: string;
|
||||
phonemes?: string[];
|
||||
phoneme_scores?: PhonemeScore[];
|
||||
highlight: 'good' | 'ok' | 'weak';
|
||||
};
|
||||
|
||||
export type PhonemeScore = {
|
||||
phoneme: string;
|
||||
accuracy: number;
|
||||
highlight: 'good' | 'ok' | 'weak';
|
||||
};
|
||||
|
||||
export type WeakPhoneme = {
|
||||
word: string;
|
||||
phoneme: string;
|
||||
accuracy: number;
|
||||
};
|
||||
|
||||
export type Attempt = {
|
||||
id: string;
|
||||
exercise_id: string;
|
||||
@@ -60,6 +73,7 @@ export type ProgressSummary = {
|
||||
total_attempts: number;
|
||||
average_score: number;
|
||||
weak_words: WordScore[] | null;
|
||||
weak_phonemes: WeakPhoneme[] | null;
|
||||
recent_attempts: Attempt[] | null;
|
||||
daily_goal_minutes: number;
|
||||
};
|
||||
|
||||
@@ -318,6 +318,22 @@ input:focus {
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.phoneme-panel {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
.phoneme-row,
|
||||
.phoneme-list {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.phoneme-row strong {
|
||||
min-width: 100px;
|
||||
}
|
||||
|
||||
.debug-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { WordScore } from '../api/types';
|
||||
|
||||
type Props = {
|
||||
words: WordScore[];
|
||||
};
|
||||
|
||||
export function PhonemeAnalysis({ words }: Props) {
|
||||
const scoredWords = words.filter((word) => word.error_type?.toLowerCase() !== 'omission' && (word.phoneme_scores?.length ?? 0) > 0);
|
||||
|
||||
return (
|
||||
<section className="panel result-panel phoneme-panel">
|
||||
<h2>Lautanalyse</h2>
|
||||
{scoredWords.length === 0 ? (
|
||||
<p className="muted">Für diese Aufnahme sind keine Lautwerte verfügbar.</p>
|
||||
) : (
|
||||
<>
|
||||
<p className="muted">Azure bewertet jeden Laut von 0 bis 100. Werte unter 75 markieren hier Übungsbedarf.</p>
|
||||
{scoredWords.map((word, wordIndex) => (
|
||||
<div className="phoneme-row" key={`${word.word}-${wordIndex}`}>
|
||||
<strong>{word.word}</strong>
|
||||
<div className="phoneme-list">
|
||||
{word.phoneme_scores?.map((phoneme, phonemeIndex) => (
|
||||
<span
|
||||
className={`word word-${phoneme.highlight}`}
|
||||
title={`${word.word}: Laut /${phoneme.phoneme}/, ${Math.round(phoneme.accuracy)} von 100 Punkten`}
|
||||
key={`${phoneme.phoneme}-${phonemeIndex}`}
|
||||
>
|
||||
/{phoneme.phoneme}/ {Math.round(phoneme.accuracy)}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { fetchNextLesson } from '../api/lessons';
|
||||
import { submitAttempt } from '../api/practice';
|
||||
import type { AttemptResponse, Exercise, Lesson } from '../api/types';
|
||||
import { AudioRecorder } from '../components/AudioRecorder';
|
||||
import { PhonemeAnalysis } from '../components/PhonemeAnalysis';
|
||||
import { PronunciationText } from '../components/PronunciationText';
|
||||
import { ScoreBadge } from '../components/ScoreBadge';
|
||||
|
||||
@@ -115,6 +116,7 @@ export function PracticePage({ initialSelection }: Props) {
|
||||
<p>{result.teacher.teacher_feedback}</p>
|
||||
<p className="muted">{result.teacher.next_recommendation}</p>
|
||||
</div>
|
||||
<PhonemeAnalysis words={result.attempt.word_scores} />
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -48,6 +48,21 @@ export function ProgressPage() {
|
||||
</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>
|
||||
|
||||
<section className="panel result-panel">
|
||||
<h2>Letzte Versuche</h2>
|
||||
<div className="attempt-list">
|
||||
|
||||
Reference in New Issue
Block a user