Initial commit

This commit is contained in:
Eugenius Naumenko
2026-06-07 22:20:57 +00:00
commit a7d8f72129
357 changed files with 168337 additions and 0 deletions
+75
View File
@@ -0,0 +1,75 @@
package config
import (
"log/slog"
"os"
"strings"
)
type Config struct {
Port string
DatabaseURL string
RedisURL string
JWTSecret string
CORSOrigins []string
AzureSpeechKey string
AzureRegion string
AzureMock bool
FlowiseBaseURL string
FlowiseChatflow string
FlowiseAPIKey string
DebugEnabled bool
DebugVerbose bool
LogLevel slog.Level
}
func Load() Config {
return Config{
Port: env("API_PORT", "8080"),
DatabaseURL: env("DATABASE_URL", "postgres://speech:speech_dev_password@localhost:5432/speech?sslmode=disable"),
RedisURL: env("REDIS_URL", "redis://localhost:6379"),
JWTSecret: env("APP_JWT_SECRET", "dev-secret-change-me"),
CORSOrigins: splitCSV(env("CORS_ORIGINS", "http://localhost:5173,http://localhost:8080")),
AzureSpeechKey: os.Getenv("AZURE_SPEECH_KEY"),
AzureRegion: os.Getenv("AZURE_SPEECH_REGION"),
AzureMock: strings.EqualFold(env("AZURE_ENABLE_MOCK", "true"), "true"),
FlowiseBaseURL: env("FLOWISE_BASE_URL", "http://localhost:3000"),
FlowiseChatflow: os.Getenv("FLOWISE_CHATFLOW_ID"),
FlowiseAPIKey: os.Getenv("FLOWISE_API_KEY"),
DebugEnabled: strings.EqualFold(env("DEBUG_ENABLED", "false"), "true"),
DebugVerbose: strings.EqualFold(env("DEBUG_VERBOSE", "false"), "true"),
LogLevel: parseLogLevel(env("LOG_LEVEL", "info")),
}
}
func env(key, fallback string) string {
if value := strings.TrimSpace(os.Getenv(key)); value != "" {
return value
}
return fallback
}
func splitCSV(value string) []string {
parts := strings.Split(value, ",")
out := make([]string, 0, len(parts))
for _, part := range parts {
part = strings.TrimSpace(part)
if part != "" {
out = append(out, part)
}
}
return out
}
func parseLogLevel(value string) slog.Level {
switch strings.ToLower(strings.TrimSpace(value)) {
case "debug":
return slog.LevelDebug
case "warn", "warning":
return slog.LevelWarn
case "error":
return slog.LevelError
default:
return slog.LevelInfo
}
}
+134
View File
@@ -0,0 +1,134 @@
package domain
import "time"
type User struct {
ID string `json:"id"`
Email string `json:"email"`
UILanguage string `json:"ui_language"`
CreatedAt time.Time `json:"created_at"`
}
type LearnerProfile struct {
ID string `json:"id"`
UserID string `json:"user_id"`
TargetLanguage string `json:"target_language"`
CEFRLevel string `json:"cefr_level"`
DailyGoalMinutes int `json:"daily_goal_minutes"`
CreatedAt time.Time `json:"created_at"`
}
type LanguageProfile struct {
Code string `json:"code"`
DisplayName string `json:"display_name"`
AzureLocale string `json:"azure_locale"`
DefaultTTSVoice string `json:"default_tts_voice"`
Voices []string `json:"voices"`
SupportsPronunciationAssessment bool `json:"supports_pronunciation_assessment"`
SupportsProsody bool `json:"supports_prosody"`
}
type Lesson struct {
ID string `json:"id"`
TargetLanguage string `json:"target_language"`
CEFRLevel string `json:"cefr_level"`
Topic string `json:"topic"`
Title string `json:"title"`
}
type Exercise struct {
ID string `json:"id"`
LessonID string `json:"lesson_id"`
TargetLanguage string `json:"target_language"`
CEFRLevel string `json:"cefr_level"`
Type string `json:"type"`
PromptText string `json:"prompt_text"`
TargetText string `json:"target_text"`
Difficulty int `json:"difficulty"`
}
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"`
}
type PronunciationResult struct {
RecognizedText string `json:"recognized_text"`
OverallScore float64 `json:"overall_score"`
AccuracyScore float64 `json:"accuracy_score"`
FluencyScore float64 `json:"fluency_score"`
CompletenessScore float64 `json:"completeness_score"`
ProsodyScore float64 `json:"prosody_score"`
WordScores []WordScore `json:"word_scores"`
Provider string `json:"provider"`
}
type Attempt struct {
ID string `json:"id"`
UserID string `json:"user_id"`
ExerciseID string `json:"exercise_id"`
TargetLanguage string `json:"target_language"`
RecognizedText string `json:"recognized_text"`
OverallScore float64 `json:"overall_score"`
AccuracyScore float64 `json:"accuracy_score"`
FluencyScore float64 `json:"fluency_score"`
CompletenessScore float64 `json:"completeness_score"`
ProsodyScore float64 `json:"prosody_score"`
WordScores []WordScore `json:"word_scores"`
TeacherFeedback string `json:"teacher_feedback"`
CreatedAt time.Time `json:"created_at"`
}
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"`
}
type Dashboard struct {
User User `json:"user"`
Profile LearnerProfile `json:"profile"`
Progress ProgressSummary `json:"progress"`
NextLesson Lesson `json:"next_lesson"`
NextExercise Exercise `json:"next_exercise"`
}
type ConversationSession struct {
ID string `json:"id"`
UserID string `json:"user_id"`
TargetLanguage string `json:"target_language"`
CEFRLevel string `json:"cefr_level"`
Status string `json:"status"`
CreatedAt time.Time `json:"created_at"`
}
type ConversationTurn struct {
ID string `json:"id"`
SessionID string `json:"session_id"`
Speaker string `json:"speaker"`
Text string `json:"text"`
AttemptID string `json:"attempt_id,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
type TeacherResponse struct {
ExerciseType string `json:"exercise_type"`
TargetText string `json:"target_text"`
TeacherFeedback string `json:"teacher_feedback"`
TTSText string `json:"tts_text"`
SSML string `json:"ssml"`
NextRecommendation string `json:"next_recommendation"`
}
type DebugDBStatus struct {
OK bool `json:"ok"`
Counts map[string]int `json:"counts"`
SeedLanguageCount int `json:"seed_language_count"`
SeedExerciseCount int `json:"seed_exercise_count"`
Error string `json:"error,omitempty"`
}
+143
View File
@@ -0,0 +1,143 @@
package httpapi
import (
"context"
"net/http"
"os"
"runtime"
"strings"
"time"
)
type debugCheck struct {
OK bool `json:"ok"`
Status string `json:"status"`
DurationMS int64 `json:"duration_ms,omitempty"`
HTTPStatus int `json:"http_status,omitempty"`
Error string `json:"error,omitempty"`
Details map[string]any `json:"details,omitempty"`
}
func (s *Server) debugStatus(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{
"request_id": requestID(r),
"debug": map[string]any{
"enabled": true,
"verbose": s.cfg.DebugVerbose,
"log_level": s.cfg.LogLevel.String(),
},
"config": s.debugConfig(),
"checks": map[string]any{
"db": s.store.DebugStatus(r.Context()),
"azure": s.azureStatus(),
"flowise": s.flowiseStatus(r.Context()),
},
})
}
func (s *Server) debugDB(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{
"request_id": requestID(r),
"db": s.store.DebugStatus(r.Context()),
})
}
func (s *Server) debugFlowise(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{
"request_id": requestID(r),
"flowise": s.flowiseStatus(r.Context()),
})
}
func (s *Server) debugAzure(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{
"request_id": requestID(r),
"azure": s.azureStatus(),
})
}
func (s *Server) debugRuntime(w http.ResponseWriter, r *http.Request) {
hostname, _ := os.Hostname()
writeJSON(w, http.StatusOK, map[string]any{
"request_id": requestID(r),
"runtime": map[string]any{
"hostname": hostname,
"go_version": runtime.Version(),
"go_os": runtime.GOOS,
"go_arch": runtime.GOARCH,
"goroutines": runtime.NumGoroutine(),
"uptime_seconds": int64(time.Since(s.started).Seconds()),
"started_at": s.started.UTC().Format(time.RFC3339),
},
})
}
func (s *Server) debugConfig() map[string]any {
return map[string]any{
"api_port": s.cfg.Port,
"cors_origins": s.cfg.CORSOrigins,
"azure_mock": s.cfg.AzureMock,
"azure_region": valueOr(s.cfg.AzureRegion, "not-set"),
"azure_speech_key_set": s.cfg.AzureSpeechKey != "",
"flowise_base_url": valueOr(s.cfg.FlowiseBaseURL, "not-set"),
"flowise_chatflow_set": s.cfg.FlowiseChatflow != "",
"flowise_api_key_set": s.cfg.FlowiseAPIKey != "",
"jwt_secret_configured": s.cfg.JWTSecret != "" && s.cfg.JWTSecret != "dev-secret-change-me",
}
}
func (s *Server) azureStatus() debugCheck {
details := map[string]any{
"mock_enabled": s.cfg.AzureMock,
"region": valueOr(s.cfg.AzureRegion, "not-set"),
"speech_key_set": s.cfg.AzureSpeechKey != "",
}
if s.cfg.AzureMock {
return debugCheck{OK: true, Status: "mock", Details: details}
}
if s.cfg.AzureSpeechKey == "" || s.cfg.AzureRegion == "" {
return debugCheck{OK: false, Status: "not_configured", Details: details}
}
details["stt_endpoint"] = "https://" + s.cfg.AzureRegion + ".stt.speech.microsoft.com"
details["tts_endpoint"] = "https://" + s.cfg.AzureRegion + ".tts.speech.microsoft.com"
return debugCheck{OK: true, Status: "configured", Details: details}
}
func (s *Server) flowiseStatus(ctx context.Context) debugCheck {
baseURL := strings.TrimRight(s.cfg.FlowiseBaseURL, "/")
details := map[string]any{
"base_url": valueOr(baseURL, "not-set"),
"chatflow_set": s.cfg.FlowiseChatflow != "",
"api_key_set": s.cfg.FlowiseAPIKey != "",
}
if baseURL == "" {
return debugCheck{OK: false, Status: "not_configured", Details: details}
}
start := time.Now()
checkCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(checkCtx, http.MethodGet, baseURL, nil)
if err != nil {
return debugCheck{OK: false, Status: "invalid_url", Error: err.Error(), Details: details}
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return debugCheck{OK: false, Status: "unreachable", Error: err.Error(), DurationMS: time.Since(start).Milliseconds(), Details: details}
}
defer resp.Body.Close()
ok := resp.StatusCode < 500
status := "reachable"
if !ok {
status = "server_error"
}
return debugCheck{
OK: ok,
Status: status,
HTTPStatus: resp.StatusCode,
DurationMS: time.Since(start).Milliseconds(),
Details: details,
}
}
+144
View File
@@ -0,0 +1,144 @@
package httpapi
import (
"context"
"crypto/rand"
"encoding/hex"
"net/http"
"strconv"
"strings"
"time"
)
type contextKey string
const userIDKey contextKey = "user_id"
const requestIDKey contextKey = "request_id"
type statusRecorder struct {
http.ResponseWriter
status int
bytes int
}
func (r *statusRecorder) WriteHeader(status int) {
r.status = status
r.ResponseWriter.WriteHeader(status)
}
func (r *statusRecorder) Write(body []byte) (int, error) {
if r.status == 0 {
r.status = http.StatusOK
}
n, err := r.ResponseWriter.Write(body)
r.bytes += n
return n, err
}
func (s *Server) requestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestID := strings.TrimSpace(r.Header.Get("X-Request-ID"))
if requestID == "" || len(requestID) > 128 {
requestID = newRequestID()
}
w.Header().Set("X-Request-ID", requestID)
ctx := context.WithValue(r.Context(), requestIDKey, requestID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func (s *Server) requestLogging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
recorder := &statusRecorder{ResponseWriter: w}
next.ServeHTTP(recorder, r)
status := recorder.status
if status == 0 {
status = http.StatusOK
}
attrs := []any{
"request_id", requestID(r),
"method", r.Method,
"path", r.URL.Path,
"status", status,
"bytes", recorder.bytes,
"duration_ms", time.Since(start).Milliseconds(),
"remote", r.RemoteAddr,
}
if userID := currentUserID(r); userID != "" {
attrs = append(attrs, "user_id", userID)
}
if status >= 500 {
s.logger.Error("http request", attrs...)
return
}
s.logger.Info("http request", attrs...)
})
}
func (s *Server) cors(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if s.isAllowedOrigin(origin) {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Vary", "Origin")
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, OPTIONS")
w.Header().Set("Access-Control-Expose-Headers", "X-Request-ID")
}
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
func (s *Server) isAllowedOrigin(origin string) bool {
if origin == "" {
return false
}
for _, allowed := range s.cfg.CORSOrigins {
if allowed == "*" || strings.EqualFold(allowed, origin) {
return true
}
}
return false
}
func (s *Server) requireAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
token := strings.TrimSpace(strings.TrimPrefix(authHeader, "Bearer "))
if token == "" || token == authHeader {
writeError(w, http.StatusUnauthorized, nil)
return
}
userID, err := s.auth.VerifyToken(token)
if err != nil {
writeError(w, http.StatusUnauthorized, err)
return
}
ctx := context.WithValue(r.Context(), userIDKey, userID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func currentUserID(r *http.Request) string {
value, _ := r.Context().Value(userIDKey).(string)
return value
}
func requestID(r *http.Request) string {
value, _ := r.Context().Value(requestIDKey).(string)
return value
}
func newRequestID() string {
var b [12]byte
if _, err := rand.Read(b[:]); err != nil {
return strconv.FormatInt(time.Now().UnixNano(), 36)
}
return hex.EncodeToString(b[:])
}
+29
View File
@@ -0,0 +1,29 @@
package httpapi
import (
"encoding/json"
"errors"
"net/http"
)
type errorResponse struct {
Error string `json:"error"`
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
func writeError(w http.ResponseWriter, status int, err error) {
if err == nil {
err = errors.New(http.StatusText(status))
}
writeJSON(w, status, errorResponse{Error: err.Error()})
}
func decodeJSON(r *http.Request, dst any) error {
defer r.Body.Close()
return json.NewDecoder(r.Body).Decode(dst)
}
+380
View File
@@ -0,0 +1,380 @@
package httpapi
import (
"context"
"encoding/base64"
"errors"
"io"
"log/slog"
"net/http"
"strings"
"time"
"speech-learning-api/internal/config"
"speech-learning-api/internal/domain"
"speech-learning-api/internal/services"
)
type DataStore interface {
GetUser(ctx context.Context, id string) (domain.User, error)
GetPrimaryProfile(ctx context.Context, userID string) (domain.LearnerProfile, error)
UpdatePreferences(ctx context.Context, userID, uiLanguage, targetLanguage, cefrLevel string, dailyGoalMinutes int) (domain.LearnerProfile, error)
ListLanguages(ctx context.Context) ([]domain.LanguageProfile, error)
GetLanguage(ctx context.Context, code string) (domain.LanguageProfile, error)
NextLessonAndExercise(ctx context.Context, profile domain.LearnerProfile) (domain.Lesson, domain.Exercise, error)
GetExercise(ctx context.Context, id string) (domain.Exercise, error)
SaveAttempt(ctx context.Context, attempt domain.Attempt) (domain.Attempt, error)
Progress(ctx context.Context, userID string, limit int) (domain.ProgressSummary, error)
CreateConversationSession(ctx context.Context, userID, targetLanguage, cefrLevel string) (domain.ConversationSession, error)
SaveConversationTurn(ctx context.Context, turn domain.ConversationTurn) (domain.ConversationTurn, error)
DebugStatus(ctx context.Context) domain.DebugDBStatus
}
type Server struct {
cfg config.Config
logger *slog.Logger
store DataStore
auth *services.AuthService
speech services.SpeechService
teacher services.TeacherAgent
started time.Time
}
func NewServer(cfg config.Config, logger *slog.Logger, store DataStore, auth *services.AuthService, speech services.SpeechService, teacher services.TeacherAgent) *Server {
return &Server{cfg: cfg, logger: logger, store: store, auth: auth, speech: speech, teacher: teacher, started: time.Now()}
}
func (s *Server) Routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /health", s.health)
mux.HandleFunc("POST /auth/register", s.register)
mux.HandleFunc("POST /auth/login", s.login)
mux.HandleFunc("POST /auth/logout", s.logout)
mux.Handle("GET /me", s.requireAuth(http.HandlerFunc(s.me)))
mux.Handle("PATCH /me/preferences", s.requireAuth(http.HandlerFunc(s.updatePreferences)))
mux.Handle("GET /languages", s.requireAuth(http.HandlerFunc(s.languages)))
mux.Handle("GET /languages/{code}/voices", s.requireAuth(http.HandlerFunc(s.languageVoices)))
mux.Handle("GET /dashboard", s.requireAuth(http.HandlerFunc(s.dashboard)))
mux.Handle("GET /progress", s.requireAuth(http.HandlerFunc(s.progress)))
mux.Handle("POST /lessons/next", s.requireAuth(http.HandlerFunc(s.nextLesson)))
mux.Handle("POST /practice/attempts", s.requireAuth(http.HandlerFunc(s.createAttempt)))
mux.Handle("POST /conversation/start", s.requireAuth(http.HandlerFunc(s.startConversation)))
mux.Handle("POST /conversation/{id}/turn", s.requireAuth(http.HandlerFunc(s.conversationTurn)))
if s.cfg.DebugEnabled {
mux.Handle("GET /debug/status", s.requireAuth(http.HandlerFunc(s.debugStatus)))
mux.Handle("GET /debug/db", s.requireAuth(http.HandlerFunc(s.debugDB)))
mux.Handle("GET /debug/flowise", s.requireAuth(http.HandlerFunc(s.debugFlowise)))
mux.Handle("GET /debug/azure", s.requireAuth(http.HandlerFunc(s.debugAzure)))
mux.Handle("GET /debug/runtime", s.requireAuth(http.HandlerFunc(s.debugRuntime)))
}
return s.requestID(s.requestLogging(s.cors(mux)))
}
func (s *Server) health(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
func (s *Server) register(w http.ResponseWriter, r *http.Request) {
var req struct {
Email string `json:"email"`
Password string `json:"password"`
UILanguage string `json:"ui_language"`
TargetLanguage string `json:"target_language"`
DailyGoalMinutes int `json:"daily_goal_minutes"`
}
if err := decodeJSON(r, &req); err != nil {
writeError(w, http.StatusBadRequest, err)
return
}
result, err := s.auth.Register(r.Context(), req.Email, req.Password, req.UILanguage, req.TargetLanguage, req.DailyGoalMinutes)
if err != nil {
writeError(w, http.StatusBadRequest, err)
return
}
writeJSON(w, http.StatusCreated, result)
}
func (s *Server) login(w http.ResponseWriter, r *http.Request) {
var req struct {
Email string `json:"email"`
Password string `json:"password"`
}
if err := decodeJSON(r, &req); err != nil {
writeError(w, http.StatusBadRequest, err)
return
}
result, err := s.auth.Login(r.Context(), req.Email, req.Password)
if err != nil {
status := http.StatusInternalServerError
if errors.Is(err, services.ErrInvalidCredentials) {
status = http.StatusUnauthorized
}
writeError(w, status, err)
return
}
writeJSON(w, http.StatusOK, result)
}
func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
func (s *Server) me(w http.ResponseWriter, r *http.Request) {
user, err := s.store.GetUser(r.Context(), currentUserID(r))
if err != nil {
writeError(w, http.StatusNotFound, err)
return
}
profile, err := s.store.GetPrimaryProfile(r.Context(), user.ID)
if err != nil {
writeError(w, http.StatusNotFound, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"user": user, "profile": profile})
}
func (s *Server) updatePreferences(w http.ResponseWriter, r *http.Request) {
var req struct {
UILanguage string `json:"ui_language"`
TargetLanguage string `json:"target_language"`
CEFRLevel string `json:"cefr_level"`
DailyGoalMinutes int `json:"daily_goal_minutes"`
}
if err := decodeJSON(r, &req); err != nil {
writeError(w, http.StatusBadRequest, err)
return
}
profile, err := s.store.UpdatePreferences(r.Context(), currentUserID(r), req.UILanguage, req.TargetLanguage, valueOr(req.CEFRLevel, "A1"), req.DailyGoalMinutes)
if err != nil {
writeError(w, http.StatusBadRequest, err)
return
}
writeJSON(w, http.StatusOK, profile)
}
func (s *Server) languages(w http.ResponseWriter, r *http.Request) {
languages, err := s.store.ListLanguages(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, err)
return
}
writeJSON(w, http.StatusOK, languages)
}
func (s *Server) languageVoices(w http.ResponseWriter, r *http.Request) {
lang, err := s.store.GetLanguage(r.Context(), r.PathValue("code"))
if err != nil {
writeError(w, http.StatusNotFound, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"code": lang.Code, "voices": lang.Voices, "default_voice": lang.DefaultTTSVoice})
}
func (s *Server) dashboard(w http.ResponseWriter, r *http.Request) {
userID := currentUserID(r)
user, err := s.store.GetUser(r.Context(), userID)
if err != nil {
writeError(w, http.StatusNotFound, err)
return
}
profile, err := s.store.GetPrimaryProfile(r.Context(), userID)
if err != nil {
writeError(w, http.StatusNotFound, err)
return
}
progress, err := s.store.Progress(r.Context(), userID, 5)
if err != nil {
writeError(w, http.StatusInternalServerError, err)
return
}
lesson, exercise, err := s.store.NextLessonAndExercise(r.Context(), profile)
if err != nil {
writeError(w, http.StatusNotFound, err)
return
}
writeJSON(w, http.StatusOK, domain.Dashboard{
User: user, Profile: profile, Progress: progress, NextLesson: lesson, NextExercise: exercise,
})
}
func (s *Server) progress(w http.ResponseWriter, r *http.Request) {
progress, err := s.store.Progress(r.Context(), currentUserID(r), 20)
if err != nil {
writeError(w, http.StatusInternalServerError, err)
return
}
writeJSON(w, http.StatusOK, progress)
}
func (s *Server) nextLesson(w http.ResponseWriter, r *http.Request) {
profile, err := s.store.GetPrimaryProfile(r.Context(), currentUserID(r))
if err != nil {
writeError(w, http.StatusNotFound, err)
return
}
lesson, exercise, err := s.store.NextLessonAndExercise(r.Context(), profile)
if err != nil {
writeError(w, http.StatusNotFound, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"lesson": lesson, "exercise": exercise})
}
func (s *Server) createAttempt(w http.ResponseWriter, r *http.Request) {
if err := r.ParseMultipartForm(24 << 20); err != nil {
writeError(w, http.StatusBadRequest, err)
return
}
exerciseID := r.FormValue("exercise_id")
exercise, err := s.store.GetExercise(r.Context(), exerciseID)
if err != nil {
writeError(w, http.StatusNotFound, err)
return
}
file, header, err := r.FormFile("audio")
if err != nil {
writeError(w, http.StatusBadRequest, errors.New("audio file is required"))
return
}
defer file.Close()
audio, err := io.ReadAll(io.LimitReader(file, 20<<20))
if err != nil {
writeError(w, http.StatusBadRequest, err)
return
}
contentType := header.Header.Get("Content-Type")
if contentType == "" {
contentType = "audio/wav"
}
result, err := s.speech.AssessPronunciation(r.Context(), services.PronunciationInput{
Audio: audio, ContentType: contentType, TargetText: exercise.TargetText, Locale: exercise.TargetLanguage,
})
if err != nil {
writeError(w, http.StatusBadGateway, err)
return
}
teacher, err := s.teacher.FeedbackForAttempt(r.Context(), exercise.TargetText, result, weakWords(result.WordScores))
if err != nil {
writeError(w, http.StatusBadGateway, err)
return
}
attempt, err := s.store.SaveAttempt(r.Context(), domain.Attempt{
UserID: currentUserID(r),
ExerciseID: exercise.ID,
TargetLanguage: exercise.TargetLanguage,
RecognizedText: result.RecognizedText,
OverallScore: result.OverallScore,
AccuracyScore: result.AccuracyScore,
FluencyScore: result.FluencyScore,
CompletenessScore: result.CompletenessScore,
ProsodyScore: result.ProsodyScore,
WordScores: result.WordScores,
TeacherFeedback: teacher.TeacherFeedback,
})
if err != nil {
writeError(w, http.StatusInternalServerError, err)
return
}
writeJSON(w, http.StatusCreated, map[string]any{"attempt": attempt, "teacher": teacher, "provider": result.Provider})
}
func (s *Server) startConversation(w http.ResponseWriter, r *http.Request) {
profile, err := s.store.GetPrimaryProfile(r.Context(), currentUserID(r))
if err != nil {
writeError(w, http.StatusNotFound, err)
return
}
session, err := s.store.CreateConversationSession(r.Context(), currentUserID(r), profile.TargetLanguage, profile.CEFRLevel)
if err != nil {
writeError(w, http.StatusInternalServerError, err)
return
}
teacher, err := s.teacher.StartConversation(r.Context(), profile.TargetLanguage, profile.CEFRLevel)
if err != nil {
writeError(w, http.StatusBadGateway, err)
return
}
lang, _ := s.store.GetLanguage(r.Context(), profile.TargetLanguage)
audio, mime, _ := s.speech.Synthesize(r.Context(), lang.AzureLocale, lang.DefaultTTSVoice, firstNonEmpty(teacher.TTSText, teacher.TargetText))
turn, _ := s.store.SaveConversationTurn(r.Context(), domain.ConversationTurn{SessionID: session.ID, Speaker: "teacher", Text: firstNonEmpty(teacher.TTSText, teacher.TargetText)})
writeJSON(w, http.StatusCreated, map[string]any{
"session": session,
"turn": turn,
"teacher": teacher,
"audio": encodeAudio(audio, mime),
})
}
func (s *Server) conversationTurn(w http.ResponseWriter, r *http.Request) {
var req struct {
Text string `json:"text"`
}
if err := decodeJSON(r, &req); err != nil {
writeError(w, http.StatusBadRequest, err)
return
}
profile, err := s.store.GetPrimaryProfile(r.Context(), currentUserID(r))
if err != nil {
writeError(w, http.StatusNotFound, err)
return
}
sessionID := r.PathValue("id")
userTurn, err := s.store.SaveConversationTurn(r.Context(), domain.ConversationTurn{SessionID: sessionID, Speaker: "learner", Text: req.Text})
if err != nil {
writeError(w, http.StatusInternalServerError, err)
return
}
teacher, err := s.teacher.ContinueConversation(r.Context(), profile.TargetLanguage, profile.CEFRLevel, req.Text)
if err != nil {
writeError(w, http.StatusBadGateway, err)
return
}
lang, _ := s.store.GetLanguage(r.Context(), profile.TargetLanguage)
audio, mime, _ := s.speech.Synthesize(r.Context(), lang.AzureLocale, lang.DefaultTTSVoice, firstNonEmpty(teacher.TTSText, teacher.TargetText))
teacherTurn, _ := s.store.SaveConversationTurn(r.Context(), domain.ConversationTurn{SessionID: sessionID, Speaker: "teacher", Text: firstNonEmpty(teacher.TTSText, teacher.TargetText)})
writeJSON(w, http.StatusOK, map[string]any{
"user_turn": userTurn,
"teacher_turn": teacherTurn,
"teacher": teacher,
"audio": encodeAudio(audio, mime),
})
}
func weakWords(words []domain.WordScore) []domain.WordScore {
out := make([]domain.WordScore, 0)
for _, word := range words {
if word.Accuracy < 75 {
out = append(out, word)
}
}
return out
}
func encodeAudio(audio []byte, mime string) map[string]string {
if len(audio) == 0 {
return nil
}
return map[string]string{
"mime_type": mime,
"base64": base64.StdEncoding.EncodeToString(audio),
}
}
func firstNonEmpty(values ...string) string {
for _, value := range values {
if strings.TrimSpace(value) != "" {
return value
}
}
return ""
}
func valueOr(value, fallback string) string {
if strings.TrimSpace(value) == "" {
return fallback
}
return value
}
+163
View File
@@ -0,0 +1,163 @@
package services
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"golang.org/x/crypto/bcrypt"
"speech-learning-api/internal/domain"
"speech-learning-api/internal/store"
)
var ErrInvalidCredentials = errors.New("invalid credentials")
type UserStore interface {
CreateUser(ctx context.Context, email, passwordHash, uiLanguage string) (domain.User, error)
GetPasswordHashByEmail(ctx context.Context, email string) (domain.User, string, error)
GetUser(ctx context.Context, id string) (domain.User, error)
GetPrimaryProfile(ctx context.Context, userID string) (domain.LearnerProfile, error)
CreateLearnerProfile(ctx context.Context, userID, targetLanguage, cefrLevel string, dailyGoalMinutes int) (domain.LearnerProfile, error)
}
type AuthService struct {
store UserStore
jwtSecret []byte
}
type AuthResult struct {
Token string `json:"token"`
User domain.User `json:"user"`
Profile domain.LearnerProfile `json:"profile"`
}
func NewAuthService(store UserStore, jwtSecret string) *AuthService {
return &AuthService{store: store, jwtSecret: []byte(jwtSecret)}
}
func (s *AuthService) Register(ctx context.Context, email, password, uiLanguage, targetLanguage string, dailyGoalMinutes int) (AuthResult, error) {
email = strings.ToLower(strings.TrimSpace(email))
if email == "" || !strings.Contains(email, "@") {
return AuthResult{}, errors.New("valid email is required")
}
if len(password) < 8 {
return AuthResult{}, errors.New("password must be at least 8 characters")
}
if uiLanguage == "" {
uiLanguage = "de-DE"
}
if targetLanguage == "" {
targetLanguage = "en-US"
}
if dailyGoalMinutes <= 0 {
dailyGoalMinutes = 10
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return AuthResult{}, err
}
user, err := s.store.CreateUser(ctx, email, string(hash), uiLanguage)
if err != nil {
return AuthResult{}, err
}
profile, err := s.store.CreateLearnerProfile(ctx, user.ID, targetLanguage, "A1", dailyGoalMinutes)
if err != nil {
return AuthResult{}, err
}
token, err := s.IssueToken(user.ID)
if err != nil {
return AuthResult{}, err
}
return AuthResult{Token: token, User: user, Profile: profile}, nil
}
func (s *AuthService) Login(ctx context.Context, email, password string) (AuthResult, error) {
user, hash, err := s.store.GetPasswordHashByEmail(ctx, email)
if err != nil {
if errors.Is(err, store.ErrNotFound) {
return AuthResult{}, ErrInvalidCredentials
}
return AuthResult{}, err
}
if err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)); err != nil {
return AuthResult{}, ErrInvalidCredentials
}
profile, err := s.store.GetPrimaryProfile(ctx, user.ID)
if errors.Is(err, store.ErrNotFound) {
profile, err = s.store.CreateLearnerProfile(ctx, user.ID, "en-US", "A1", 10)
}
if err != nil {
return AuthResult{}, err
}
token, err := s.IssueToken(user.ID)
if err != nil {
return AuthResult{}, err
}
return AuthResult{Token: token, User: user, Profile: profile}, nil
}
func (s *AuthService) IssueToken(userID string) (string, error) {
header := map[string]string{"alg": "HS256", "typ": "JWT"}
payload := map[string]any{
"sub": userID,
"exp": time.Now().Add(24 * time.Hour).Unix(),
"iat": time.Now().Unix(),
}
headerJSON, err := json.Marshal(header)
if err != nil {
return "", err
}
payloadJSON, err := json.Marshal(payload)
if err != nil {
return "", err
}
enc := base64.RawURLEncoding
unsigned := enc.EncodeToString(headerJSON) + "." + enc.EncodeToString(payloadJSON)
sig := hmacSHA256(unsigned, s.jwtSecret)
return unsigned + "." + enc.EncodeToString(sig), nil
}
func (s *AuthService) VerifyToken(token string) (string, error) {
parts := strings.Split(token, ".")
if len(parts) != 3 {
return "", errors.New("invalid token")
}
unsigned := parts[0] + "." + parts[1]
expected := hmacSHA256(unsigned, s.jwtSecret)
actual, err := base64.RawURLEncoding.DecodeString(parts[2])
if err != nil {
return "", err
}
if !hmac.Equal(expected, actual) {
return "", errors.New("invalid signature")
}
payloadJSON, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return "", err
}
var claims struct {
Subject string `json:"sub"`
Expiry int64 `json:"exp"`
}
if err := json.Unmarshal(payloadJSON, &claims); err != nil {
return "", err
}
if claims.Subject == "" || time.Now().Unix() > claims.Expiry {
return "", fmt.Errorf("token expired or missing subject")
}
return claims.Subject, nil
}
func hmacSHA256(value string, secret []byte) []byte {
mac := hmac.New(sha256.New, secret)
mac.Write([]byte(value))
return mac.Sum(nil)
}
+32
View File
@@ -0,0 +1,32 @@
package services
import "testing"
func TestAuthServiceIssueAndVerifyToken(t *testing.T) {
auth := NewAuthService(nil, "test-secret")
token, err := auth.IssueToken("usr_test")
if err != nil {
t.Fatalf("issue token: %v", err)
}
userID, err := auth.VerifyToken(token)
if err != nil {
t.Fatalf("verify token: %v", err)
}
if userID != "usr_test" {
t.Fatalf("expected usr_test, got %s", userID)
}
}
func TestAuthServiceRejectsTamperedToken(t *testing.T) {
auth := NewAuthService(nil, "test-secret")
token, err := auth.IssueToken("usr_test")
if err != nil {
t.Fatalf("issue token: %v", err)
}
if _, err := auth.VerifyToken(token + "x"); err == nil {
t.Fatal("expected tampered token to fail")
}
}
+187
View File
@@ -0,0 +1,187 @@
package services
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"strings"
"time"
"speech-learning-api/internal/config"
"speech-learning-api/internal/domain"
)
type TeacherAgent interface {
FeedbackForAttempt(ctx context.Context, targetText string, result domain.PronunciationResult, weakWords []domain.WordScore) (domain.TeacherResponse, error)
StartConversation(ctx context.Context, targetLanguage, cefrLevel string) (domain.TeacherResponse, error)
ContinueConversation(ctx context.Context, targetLanguage, cefrLevel, userText string) (domain.TeacherResponse, error)
}
type FlowiseTeacher struct {
cfg config.Config
client *http.Client
logger *slog.Logger
}
func NewFlowiseTeacher(cfg config.Config, logger *slog.Logger) *FlowiseTeacher {
return &FlowiseTeacher{
cfg: cfg,
client: &http.Client{
Timeout: 30 * time.Second,
},
logger: logger,
}
}
func (f *FlowiseTeacher) FeedbackForAttempt(ctx context.Context, targetText string, result domain.PronunciationResult, weakWords []domain.WordScore) (domain.TeacherResponse, error) {
prompt := map[string]any{
"task": "practice_feedback",
"target_text": targetText,
"recognized_text": result.RecognizedText,
"scores": result,
"weak_words": weakWords,
"rules": "Answer in German. A1 learner. Max two corrections. Return valid JSON only.",
}
return f.ask(ctx, prompt, mockFeedback(targetText, result))
}
func (f *FlowiseTeacher) StartConversation(ctx context.Context, targetLanguage, cefrLevel string) (domain.TeacherResponse, error) {
prompt := map[string]any{
"task": "start_conversation",
"target_language": targetLanguage,
"cefr_level": cefrLevel,
"rules": "Create a simple A1 roleplay. Return valid JSON only.",
}
return f.ask(ctx, prompt, domain.TeacherResponse{
ExerciseType: "conversation",
TargetText: "Hello. What is your name?",
TeacherFeedback: "Wir starten sehr einfach. Antworte mit: My name is ...",
TTSText: "Hello. What is your name?",
NextRecommendation: "Antworten: My name is ...",
})
}
func (f *FlowiseTeacher) ContinueConversation(ctx context.Context, targetLanguage, cefrLevel, userText string) (domain.TeacherResponse, error) {
prompt := map[string]any{
"task": "continue_conversation",
"target_language": targetLanguage,
"cefr_level": cefrLevel,
"user_text": userText,
"rules": "Continue a simple A1 conversation. Return valid JSON only.",
}
return f.ask(ctx, prompt, domain.TeacherResponse{
ExerciseType: "conversation",
TargetText: "Nice to meet you. Where are you from?",
TeacherFeedback: "Gut. Jetzt uebe einen kurzen Satz mit Herkunft.",
TTSText: "Nice to meet you. Where are you from?",
NextRecommendation: "Antworten: I am from ...",
})
}
func (f *FlowiseTeacher) ask(ctx context.Context, payload any, fallback domain.TeacherResponse) (domain.TeacherResponse, error) {
if f.cfg.FlowiseChatflow == "" || f.cfg.FlowiseBaseURL == "" {
return fallback, nil
}
body, _ := json.Marshal(payload)
question := string(body)
reqBody, _ := json.Marshal(map[string]any{
"question": question,
})
endpoint := strings.TrimRight(f.cfg.FlowiseBaseURL, "/") + "/api/v1/prediction/" + f.cfg.FlowiseChatflow
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(reqBody))
if err != nil {
return fallback, err
}
req.Header.Set("Content-Type", "application/json")
if f.cfg.FlowiseAPIKey != "" {
req.Header.Set("Authorization", "Bearer "+f.cfg.FlowiseAPIKey)
}
resp, err := f.client.Do(req)
if err != nil {
f.logger.Warn("flowise unavailable, using fallback", "error", err)
return fallback, nil
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return fallback, err
}
if resp.StatusCode >= 300 {
f.logger.Warn("flowise returned error, using fallback", "status", resp.StatusCode, "body", string(respBody))
return fallback, nil
}
var envelope struct {
Text string `json:"text"`
JSON json.RawMessage `json:"json"`
}
if err := json.Unmarshal(respBody, &envelope); err == nil {
if envelope.Text != "" {
if parsed, ok := parseTeacherResponse(envelope.Text); ok {
return parsed, nil
}
fallback.TeacherFeedback = envelope.Text
return fallback, nil
}
if len(envelope.JSON) > 0 && string(envelope.JSON) != "null" {
if parsed, ok := parseTeacherResponseJSON(envelope.JSON); ok {
return parsed, nil
}
}
}
if parsed, ok := parseTeacherResponse(string(respBody)); ok {
return parsed, nil
}
f.logger.Warn("flowise response not parseable, using fallback", "body", string(respBody))
return fallback, nil
}
func parseTeacherResponse(value string) (domain.TeacherResponse, bool) {
value = strings.TrimSpace(value)
value = strings.TrimPrefix(value, "```json")
value = strings.TrimPrefix(value, "```")
value = strings.TrimSuffix(value, "```")
var out domain.TeacherResponse
if err := json.Unmarshal([]byte(strings.TrimSpace(value)), &out); err != nil {
return domain.TeacherResponse{}, false
}
return out, out.TeacherFeedback != "" || out.TargetText != "" || out.TTSText != ""
}
func parseTeacherResponseJSON(value json.RawMessage) (domain.TeacherResponse, bool) {
if parsed, ok := parseTeacherResponse(string(value)); ok {
return parsed, true
}
var text string
if err := json.Unmarshal(value, &text); err != nil {
return domain.TeacherResponse{}, false
}
return parseTeacherResponse(text)
}
func mockFeedback(targetText string, result domain.PronunciationResult) domain.TeacherResponse {
weak := "den roten Woertern"
for _, word := range result.WordScores {
if word.Highlight == "weak" {
weak = fmt.Sprintf("'%s'", word.Word)
break
}
}
feedback := fmt.Sprintf("Guter Versuch. Uebe jetzt besonders %s. Sprich langsam und halte die Endlaute klar.", weak)
if result.OverallScore >= 85 {
feedback = "Sehr solide. Wiederhole den Satz einmal etwas natuerlicher und mit ruhigem Rhythmus."
}
return domain.TeacherResponse{
ExerciseType: "repeat_sentence",
TargetText: targetText,
TeacherFeedback: feedback,
TTSText: targetText,
NextRecommendation: "Noch einmal sprechen und auf die markierten Woerter achten.",
}
}
+115
View File
@@ -0,0 +1,115 @@
package services
import (
"context"
"encoding/json"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
"speech-learning-api/internal/config"
"speech-learning-api/internal/domain"
)
func TestParseTeacherResponse(t *testing.T) {
response, ok := parseTeacherResponse(`{
"exercise_type": "repeat_sentence",
"target_text": "Hello.",
"teacher_feedback": "Gut.",
"tts_text": "Hello.",
"ssml": "",
"next_recommendation": "Noch einmal."
}`)
if !ok {
t.Fatal("expected response to parse")
}
if response.TargetText != "Hello." {
t.Fatalf("unexpected target text %q", response.TargetText)
}
}
func TestParseTeacherResponseJSONFromObject(t *testing.T) {
response, ok := parseTeacherResponseJSON(json.RawMessage(`{
"exercise_type": "repeat_sentence",
"target_text": "Hello.",
"teacher_feedback": "Gut.",
"tts_text": "Hello.",
"ssml": "",
"next_recommendation": "Noch einmal."
}`))
if !ok {
t.Fatal("expected response to parse")
}
if response.TeacherFeedback != "Gut." {
t.Fatalf("unexpected feedback %q", response.TeacherFeedback)
}
}
func TestParseTeacherResponseJSONFromString(t *testing.T) {
response, ok := parseTeacherResponseJSON(json.RawMessage(`"{\"exercise_type\":\"repeat_sentence\",\"target_text\":\"Hello.\",\"teacher_feedback\":\"Gut.\",\"tts_text\":\"Hello.\",\"ssml\":\"\",\"next_recommendation\":\"Noch einmal.\"}"`))
if !ok {
t.Fatal("expected response to parse")
}
if response.NextRecommendation != "Noch einmal." {
t.Fatalf("unexpected recommendation %q", response.NextRecommendation)
}
}
func TestFlowiseAskSendsQuestionOnly(t *testing.T) {
var requestBody map[string]json.RawMessage
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/v1/prediction/chatflow-id" {
t.Fatalf("unexpected path %q", r.URL.Path)
}
if r.Header.Get("Authorization") != "Bearer api-key" {
t.Fatalf("unexpected authorization header %q", r.Header.Get("Authorization"))
}
if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil {
t.Fatalf("decode request body: %v", err)
}
response := domain.TeacherResponse{
ExerciseType: "conversation",
TargetText: "Hello.",
TeacherFeedback: "Gut.",
TTSText: "Hello.",
NextRecommendation: "Noch einmal.",
}
responseText, err := json.Marshal(response)
if err != nil {
t.Fatalf("marshal response: %v", err)
}
if err := json.NewEncoder(w).Encode(map[string]string{"text": string(responseText)}); err != nil {
t.Fatalf("encode response: %v", err)
}
}))
defer server.Close()
teacher := NewFlowiseTeacher(config.Config{
FlowiseBaseURL: server.URL,
FlowiseChatflow: "chatflow-id",
FlowiseAPIKey: "api-key",
}, slog.New(slog.NewTextHandler(io.Discard, nil)))
response, err := teacher.ask(context.Background(), map[string]any{"task": "start_conversation"}, domain.TeacherResponse{
TeacherFeedback: "fallback",
})
if err != nil {
t.Fatalf("ask: %v", err)
}
if response.TeacherFeedback != "Gut." {
t.Fatalf("unexpected feedback %q", response.TeacherFeedback)
}
if _, ok := requestBody["question"]; !ok {
t.Fatal("expected question in request body")
}
if _, ok := requestBody["form"]; ok {
t.Fatal("did not expect form in request body")
}
}
+290
View File
@@ -0,0 +1,290 @@
package services
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"math"
"net/http"
"net/url"
"strings"
"time"
"speech-learning-api/internal/config"
"speech-learning-api/internal/domain"
)
type SpeechService interface {
AssessPronunciation(ctx context.Context, input PronunciationInput) (domain.PronunciationResult, error)
Synthesize(ctx context.Context, locale, voice, text string) ([]byte, string, error)
}
type PronunciationInput struct {
Audio []byte
ContentType string
TargetText string
Locale string
}
type AzureSpeechService struct {
cfg config.Config
client *http.Client
logger *slog.Logger
}
func NewAzureSpeechService(cfg config.Config, logger *slog.Logger) *AzureSpeechService {
return &AzureSpeechService{
cfg: cfg,
client: &http.Client{
Timeout: 45 * time.Second,
},
logger: logger,
}
}
func (s *AzureSpeechService) AssessPronunciation(ctx context.Context, input PronunciationInput) (domain.PronunciationResult, error) {
if input.TargetText == "" {
return domain.PronunciationResult{}, errors.New("target text is required")
}
if s.cfg.AzureMock || s.cfg.AzureSpeechKey == "" || s.cfg.AzureRegion == "" {
return mockPronunciation(input.TargetText), nil
}
endpoint := fmt.Sprintf("https://%s.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=%s",
s.cfg.AzureRegion, url.QueryEscape(valueOr(input.Locale, "en-US")))
assessmentConfig := map[string]any{
"ReferenceText": input.TargetText,
"GradingSystem": "HundredMark",
"Granularity": "Phoneme",
"Dimension": "Comprehensive",
"EnableMiscue": true,
"PhonemeAlphabet": "IPA",
}
assessmentJSON, _ := json.Marshal(assessmentConfig)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(input.Audio))
if err != nil {
return domain.PronunciationResult{}, err
}
req.Header.Set("Ocp-Apim-Subscription-Key", s.cfg.AzureSpeechKey)
req.Header.Set("Accept", "application/json;text/xml")
req.Header.Set("Content-Type", contentTypeForAzure(input.ContentType))
req.Header.Set("Pronunciation-Assessment", base64.StdEncoding.EncodeToString(assessmentJSON))
resp, err := s.client.Do(req)
if err != nil {
return domain.PronunciationResult{}, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return domain.PronunciationResult{}, err
}
if resp.StatusCode >= 300 {
s.logger.Warn("azure pronunciation failed", "status", resp.StatusCode, "body", string(body))
return domain.PronunciationResult{}, fmt.Errorf("azure pronunciation status %d", resp.StatusCode)
}
return parseAzurePronunciation(body)
}
func (s *AzureSpeechService) Synthesize(ctx context.Context, locale, voice, text string) ([]byte, string, error) {
if strings.TrimSpace(text) == "" {
return nil, "", errors.New("tts text is required")
}
if s.cfg.AzureMock || s.cfg.AzureSpeechKey == "" || s.cfg.AzureRegion == "" {
return nil, "", nil
}
locale = valueOr(locale, "en-US")
voice = valueOr(voice, "en-US-JennyNeural")
ssml := fmt.Sprintf(`<speak version="1.0" xml:lang="%s"><voice name="%s">%s</voice></speak>`, locale, voice, xmlEscape(text))
endpoint := fmt.Sprintf("https://%s.tts.speech.microsoft.com/cognitiveservices/v1", s.cfg.AzureRegion)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(ssml))
if err != nil {
return nil, "", err
}
req.Header.Set("Ocp-Apim-Subscription-Key", s.cfg.AzureSpeechKey)
req.Header.Set("Content-Type", "application/ssml+xml")
req.Header.Set("X-Microsoft-OutputFormat", "audio-24khz-48kbitrate-mono-mp3")
req.Header.Set("User-Agent", "speech-learning-app")
resp, err := s.client.Do(req)
if err != nil {
return nil, "", err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, "", err
}
if resp.StatusCode >= 300 {
return nil, "", fmt.Errorf("azure tts status %d: %s", resp.StatusCode, string(body))
}
return body, "audio/mpeg", nil
}
type azurePronunciationResponse struct {
RecognitionStatus string `json:"RecognitionStatus"`
DisplayText string `json:"DisplayText"`
NBest []struct {
Display string `json:"Display"`
PronScore float64 `json:"PronScore"`
AccuracyScore float64 `json:"AccuracyScore"`
FluencyScore float64 `json:"FluencyScore"`
CompletenessScore float64 `json:"CompletenessScore"`
ProsodyScore float64 `json:"ProsodyScore"`
PronunciationAssessment struct {
PronScore float64 `json:"PronScore"`
AccuracyScore float64 `json:"AccuracyScore"`
FluencyScore float64 `json:"FluencyScore"`
CompletenessScore float64 `json:"CompletenessScore"`
ProsodyScore float64 `json:"ProsodyScore"`
} `json:"PronunciationAssessment"`
Words []struct {
Word string `json:"Word"`
ErrorType string `json:"ErrorType"`
AccuracyScore float64 `json:"AccuracyScore"`
PronunciationAssessment struct {
AccuracyScore float64 `json:"AccuracyScore"`
ErrorType string `json:"ErrorType"`
} `json:"PronunciationAssessment"`
Phonemes []struct {
Phoneme string `json:"Phoneme"`
} `json:"Phonemes"`
} `json:"Words"`
} `json:"NBest"`
}
func parseAzurePronunciation(body []byte) (domain.PronunciationResult, error) {
var raw azurePronunciationResponse
if err := json.Unmarshal(body, &raw); err != nil {
return domain.PronunciationResult{}, err
}
if len(raw.NBest) == 0 {
return domain.PronunciationResult{}, fmt.Errorf("azure response has no NBest result")
}
best := raw.NBest[0]
result := domain.PronunciationResult{
RecognizedText: firstNonEmpty(best.Display, raw.DisplayText),
OverallScore: firstScore(best.PronScore, best.PronunciationAssessment.PronScore),
AccuracyScore: firstScore(best.AccuracyScore, best.PronunciationAssessment.AccuracyScore),
FluencyScore: firstScore(best.FluencyScore, best.PronunciationAssessment.FluencyScore),
CompletenessScore: firstScore(best.CompletenessScore, best.PronunciationAssessment.CompletenessScore),
ProsodyScore: firstScore(best.ProsodyScore, best.PronunciationAssessment.ProsodyScore),
Provider: "azure",
}
for _, word := range best.Words {
phonemes := make([]string, 0, len(word.Phonemes))
for _, phoneme := range word.Phonemes {
if phoneme.Phoneme != "" {
phonemes = append(phonemes, phoneme.Phoneme)
}
}
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),
})
}
return result, nil
}
func mockPronunciation(target string) domain.PronunciationResult {
words := strings.Fields(target)
wordScores := make([]domain.WordScore, 0, len(words))
total := 0.0
for i, word := range words {
clean := strings.Trim(word, ".,!?;:")
score := 92.0 - float64((len(clean)+i*7)%32)
if strings.Contains(strings.ToLower(clean), "th") {
score -= 10
}
score = math.Max(48, math.Min(97, score))
total += score
wordScores = append(wordScores, domain.WordScore{
Word: clean,
Accuracy: score,
Highlight: highlightFor(score),
})
}
avg := 82.0
if len(wordScores) > 0 {
avg = total / float64(len(wordScores))
}
return domain.PronunciationResult{
RecognizedText: target,
OverallScore: avg,
AccuracyScore: avg,
FluencyScore: math.Min(98, avg+4),
CompletenessScore: math.Min(100, avg+6),
ProsodyScore: math.Max(50, avg-3),
WordScores: wordScores,
Provider: "mock",
}
}
func highlightFor(score float64) string {
switch {
case score >= 85:
return "good"
case score >= 70:
return "ok"
default:
return "weak"
}
}
func contentTypeForAzure(contentType string) string {
if strings.Contains(contentType, "wav") {
return "audio/wav; codecs=audio/pcm; samplerate=16000"
}
if strings.TrimSpace(contentType) != "" {
return contentType
}
return "audio/wav; codecs=audio/pcm; samplerate=16000"
}
func xmlEscape(value string) string {
value = strings.ReplaceAll(value, "&", "&amp;")
value = strings.ReplaceAll(value, "<", "&lt;")
value = strings.ReplaceAll(value, ">", "&gt;")
value = strings.ReplaceAll(value, `"`, "&quot;")
value = strings.ReplaceAll(value, "'", "&apos;")
return value
}
func firstNonEmpty(values ...string) string {
for _, value := range values {
if strings.TrimSpace(value) != "" {
return value
}
}
return ""
}
func firstScore(values ...float64) float64 {
for _, value := range values {
if value != 0 {
return value
}
}
return 0
}
func valueOr(value, fallback string) string {
if strings.TrimSpace(value) == "" {
return fallback
}
return value
}
+60
View File
@@ -0,0 +1,60 @@
package services
import "testing"
func TestMockPronunciationReturnsWordScores(t *testing.T) {
result := mockPronunciation("Hello, my name is Anna.")
if result.Provider != "mock" {
t.Fatalf("expected mock provider, got %s", result.Provider)
}
if len(result.WordScores) != 5 {
t.Fatalf("expected 5 word scores, got %d", len(result.WordScores))
}
if result.OverallScore <= 0 {
t.Fatalf("expected positive score, got %f", result.OverallScore)
}
}
func TestParseAzurePronunciationTopLevelScores(t *testing.T) {
body := []byte(`{
"RecognitionStatus": "Success",
"DisplayText": "Can I have a coffee please?",
"NBest": [{
"Display": "Can I have a coffee please?",
"AccuracyScore": 94.0,
"FluencyScore": 99.0,
"CompletenessScore": 100.0,
"PronScore": 96.2,
"Words": [{
"Word": "can",
"AccuracyScore": 94.0,
"ErrorType": "None",
"Phonemes": [{"Phoneme": "k"}, {"Phoneme": "ae"}, {"Phoneme": "n"}]
}]
}]
}`)
result, err := parseAzurePronunciation(body)
if err != nil {
t.Fatalf("parse azure pronunciation: %v", err)
}
if result.Provider != "azure" {
t.Fatalf("expected azure provider, got %s", result.Provider)
}
if result.OverallScore != 96.2 {
t.Fatalf("expected overall score 96.2, got %f", result.OverallScore)
}
if result.AccuracyScore != 94 {
t.Fatalf("expected accuracy score 94, got %f", result.AccuracyScore)
}
if len(result.WordScores) != 1 {
t.Fatalf("expected one word score, got %d", len(result.WordScores))
}
if result.WordScores[0].Accuracy != 94 {
t.Fatalf("expected word accuracy 94, got %f", result.WordScores[0].Accuracy)
}
if result.WordScores[0].Highlight != "good" {
t.Fatalf("expected good highlight, got %s", result.WordScores[0].Highlight)
}
}
+544
View File
@@ -0,0 +1,544 @@
package store
import (
"context"
"crypto/rand"
"database/sql"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"strings"
"speech-learning-api/internal/domain"
)
var ErrNotFound = errors.New("not found")
type PostgresStore struct {
db *sql.DB
}
func NewPostgresStore(db *sql.DB) *PostgresStore {
return &PostgresStore{db: db}
}
func NewID(prefix string) string {
var b [12]byte
if _, err := rand.Read(b[:]); err != nil {
panic(err)
}
return prefix + "_" + hex.EncodeToString(b[:])
}
func (s *PostgresStore) Init(ctx context.Context) error {
if _, err := s.db.ExecContext(ctx, schemaSQL); err != nil {
return err
}
for _, stmt := range seedSQL {
if _, err := s.db.ExecContext(ctx, stmt); err != nil {
return err
}
}
return nil
}
func (s *PostgresStore) DebugStatus(ctx context.Context) domain.DebugDBStatus {
status := domain.DebugDBStatus{
Counts: map[string]int{},
}
if err := s.db.PingContext(ctx); err != nil {
status.Error = err.Error()
return status
}
status.OK = true
for _, table := range []string{"users", "learner_profiles", "language_profiles", "lessons", "exercises", "attempts", "conversation_sessions"} {
var count int
if err := s.db.QueryRowContext(ctx, fmt.Sprintf("SELECT COUNT(*) FROM %s", table)).Scan(&count); err != nil {
status.OK = false
status.Error = err.Error()
return status
}
status.Counts[table] = count
}
_ = s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM language_profiles WHERE code = 'en-US'`).Scan(&status.SeedLanguageCount)
_ = s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM exercises WHERE target_language = 'en-US' AND cefr_level = 'A1'`).Scan(&status.SeedExerciseCount)
return status
}
func (s *PostgresStore) CreateUser(ctx context.Context, email, passwordHash, uiLanguage string) (domain.User, error) {
user := domain.User{ID: NewID("usr"), Email: strings.ToLower(strings.TrimSpace(email)), UILanguage: uiLanguage}
row := s.db.QueryRowContext(ctx, `
INSERT INTO users (id, email, password_hash, ui_language)
VALUES ($1, $2, $3, $4)
RETURNING id, email, ui_language, created_at
`, user.ID, user.Email, passwordHash, uiLanguage)
if err := row.Scan(&user.ID, &user.Email, &user.UILanguage, &user.CreatedAt); err != nil {
return domain.User{}, err
}
return user, nil
}
func (s *PostgresStore) GetPasswordHashByEmail(ctx context.Context, email string) (domain.User, string, error) {
var user domain.User
var hash string
row := s.db.QueryRowContext(ctx, `
SELECT id, email, password_hash, ui_language, created_at
FROM users
WHERE email = $1
`, strings.ToLower(strings.TrimSpace(email)))
if err := row.Scan(&user.ID, &user.Email, &hash, &user.UILanguage, &user.CreatedAt); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return domain.User{}, "", ErrNotFound
}
return domain.User{}, "", err
}
return user, hash, nil
}
func (s *PostgresStore) GetUser(ctx context.Context, id string) (domain.User, error) {
var user domain.User
row := s.db.QueryRowContext(ctx, `
SELECT id, email, ui_language, created_at
FROM users
WHERE id = $1
`, id)
if err := row.Scan(&user.ID, &user.Email, &user.UILanguage, &user.CreatedAt); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return domain.User{}, ErrNotFound
}
return domain.User{}, err
}
return user, nil
}
func (s *PostgresStore) CreateLearnerProfile(ctx context.Context, userID, targetLanguage, cefrLevel string, dailyGoalMinutes int) (domain.LearnerProfile, error) {
profile := domain.LearnerProfile{
ID: NewID("lrn"),
UserID: userID,
TargetLanguage: targetLanguage,
CEFRLevel: cefrLevel,
DailyGoalMinutes: dailyGoalMinutes,
}
row := s.db.QueryRowContext(ctx, `
INSERT INTO learner_profiles (id, user_id, target_language, cefr_level, daily_goal_minutes)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (user_id, target_language) DO UPDATE SET
cefr_level = EXCLUDED.cefr_level,
daily_goal_minutes = EXCLUDED.daily_goal_minutes
RETURNING id, user_id, target_language, cefr_level, daily_goal_minutes, created_at
`, profile.ID, userID, targetLanguage, cefrLevel, dailyGoalMinutes)
if err := row.Scan(&profile.ID, &profile.UserID, &profile.TargetLanguage, &profile.CEFRLevel, &profile.DailyGoalMinutes, &profile.CreatedAt); err != nil {
return domain.LearnerProfile{}, err
}
return profile, nil
}
func (s *PostgresStore) GetPrimaryProfile(ctx context.Context, userID string) (domain.LearnerProfile, error) {
var p domain.LearnerProfile
row := s.db.QueryRowContext(ctx, `
SELECT id, user_id, target_language, cefr_level, daily_goal_minutes, created_at
FROM learner_profiles
WHERE user_id = $1
ORDER BY created_at
LIMIT 1
`, userID)
if err := row.Scan(&p.ID, &p.UserID, &p.TargetLanguage, &p.CEFRLevel, &p.DailyGoalMinutes, &p.CreatedAt); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return domain.LearnerProfile{}, ErrNotFound
}
return domain.LearnerProfile{}, err
}
return p, nil
}
func (s *PostgresStore) UpdatePreferences(ctx context.Context, userID, uiLanguage, targetLanguage, cefrLevel string, dailyGoalMinutes int) (domain.LearnerProfile, error) {
if uiLanguage != "" {
if _, err := s.db.ExecContext(ctx, `UPDATE users SET ui_language = $1 WHERE id = $2`, uiLanguage, userID); err != nil {
return domain.LearnerProfile{}, err
}
}
if dailyGoalMinutes <= 0 {
dailyGoalMinutes = 10
}
return s.CreateLearnerProfile(ctx, userID, valueOr(targetLanguage, "en-US"), valueOr(cefrLevel, "A1"), dailyGoalMinutes)
}
func (s *PostgresStore) ListLanguages(ctx context.Context) ([]domain.LanguageProfile, error) {
rows, err := s.db.QueryContext(ctx, `
SELECT code, display_name, azure_locale, default_tts_voice, voices_json,
supports_pronunciation_assessment, supports_prosody
FROM language_profiles
ORDER BY code
`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []domain.LanguageProfile
for rows.Next() {
item, err := scanLanguage(rows)
if err != nil {
return nil, err
}
out = append(out, item)
}
return out, rows.Err()
}
func (s *PostgresStore) GetLanguage(ctx context.Context, code string) (domain.LanguageProfile, error) {
row := s.db.QueryRowContext(ctx, `
SELECT code, display_name, azure_locale, default_tts_voice, voices_json,
supports_pronunciation_assessment, supports_prosody
FROM language_profiles
WHERE code = $1
`, code)
lang, err := scanLanguage(row)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return domain.LanguageProfile{}, ErrNotFound
}
return domain.LanguageProfile{}, err
}
return lang, nil
}
func (s *PostgresStore) NextLessonAndExercise(ctx context.Context, profile domain.LearnerProfile) (domain.Lesson, domain.Exercise, error) {
var lesson domain.Lesson
var exercise domain.Exercise
row := s.db.QueryRowContext(ctx, `
SELECT l.id, l.target_language, l.cefr_level, l.topic, l.title,
e.id, e.lesson_id, e.target_language, e.cefr_level, e.type,
e.prompt_text, e.target_text, e.difficulty
FROM exercises e
JOIN lessons l ON l.id = e.lesson_id
WHERE e.target_language = $1 AND e.cefr_level = $2
ORDER BY (
SELECT COUNT(*)
FROM attempts a
WHERE a.exercise_id = e.id AND a.user_id = $3
), e.difficulty, e.id
LIMIT 1
`, profile.TargetLanguage, profile.CEFRLevel, profile.UserID)
if err := row.Scan(
&lesson.ID, &lesson.TargetLanguage, &lesson.CEFRLevel, &lesson.Topic, &lesson.Title,
&exercise.ID, &exercise.LessonID, &exercise.TargetLanguage, &exercise.CEFRLevel, &exercise.Type,
&exercise.PromptText, &exercise.TargetText, &exercise.Difficulty,
); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return domain.Lesson{}, domain.Exercise{}, ErrNotFound
}
return domain.Lesson{}, domain.Exercise{}, err
}
return lesson, exercise, nil
}
func (s *PostgresStore) GetExercise(ctx context.Context, id string) (domain.Exercise, error) {
var e domain.Exercise
row := s.db.QueryRowContext(ctx, `
SELECT id, lesson_id, target_language, cefr_level, type, prompt_text, target_text, difficulty
FROM exercises
WHERE id = $1
`, id)
if err := row.Scan(&e.ID, &e.LessonID, &e.TargetLanguage, &e.CEFRLevel, &e.Type, &e.PromptText, &e.TargetText, &e.Difficulty); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return domain.Exercise{}, ErrNotFound
}
return domain.Exercise{}, err
}
return e, nil
}
func (s *PostgresStore) SaveAttempt(ctx context.Context, attempt domain.Attempt) (domain.Attempt, error) {
if attempt.ID == "" {
attempt.ID = NewID("att")
}
wordScores, err := json.Marshal(attempt.WordScores)
if err != nil {
return domain.Attempt{}, err
}
row := s.db.QueryRowContext(ctx, `
INSERT INTO attempts (
id, user_id, exercise_id, target_language, recognized_text,
overall_score, accuracy_score, fluency_score, completeness_score, prosody_score,
word_scores_json, teacher_feedback
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
RETURNING created_at
`, attempt.ID, attempt.UserID, attempt.ExerciseID, attempt.TargetLanguage, attempt.RecognizedText,
attempt.OverallScore, attempt.AccuracyScore, attempt.FluencyScore, attempt.CompletenessScore, attempt.ProsodyScore,
string(wordScores), attempt.TeacherFeedback)
if err := row.Scan(&attempt.CreatedAt); err != nil {
return domain.Attempt{}, err
}
return attempt, nil
}
func (s *PostgresStore) Progress(ctx context.Context, userID string, limit int) (domain.ProgressSummary, error) {
if limit <= 0 {
limit = 10
}
var summary domain.ProgressSummary
if err := s.db.QueryRowContext(ctx, `
SELECT COUNT(*), COALESCE(AVG(overall_score), 0)
FROM attempts
WHERE user_id = $1
`, userID).Scan(&summary.TotalAttempts, &summary.AverageScore); err != nil {
return domain.ProgressSummary{}, err
}
profile, err := s.GetPrimaryProfile(ctx, userID)
if err == nil {
summary.DailyGoalMinutes = profile.DailyGoalMinutes
}
rows, err := s.db.QueryContext(ctx, `
SELECT id, user_id, exercise_id, target_language, recognized_text,
overall_score, accuracy_score, fluency_score, completeness_score, prosody_score,
word_scores_json, teacher_feedback, created_at
FROM attempts
WHERE user_id = $1
ORDER BY created_at DESC
LIMIT $2
`, userID, limit)
if err != nil {
return domain.ProgressSummary{}, err
}
defer rows.Close()
weakByWord := map[string]domain.WordScore{}
for rows.Next() {
attempt, err := scanAttempt(rows)
if err != nil {
return domain.ProgressSummary{}, err
}
summary.RecentAttempts = append(summary.RecentAttempts, attempt)
for _, word := range attempt.WordScores {
if word.Accuracy < 75 {
existing, ok := weakByWord[strings.ToLower(word.Word)]
if !ok || word.Accuracy < existing.Accuracy {
weakByWord[strings.ToLower(word.Word)] = word
}
}
}
}
for _, word := range weakByWord {
summary.WeakWords = append(summary.WeakWords, word)
}
return summary, rows.Err()
}
func (s *PostgresStore) CreateConversationSession(ctx context.Context, userID, targetLanguage, cefrLevel string) (domain.ConversationSession, error) {
session := domain.ConversationSession{
ID: NewID("con"),
UserID: userID,
TargetLanguage: targetLanguage,
CEFRLevel: cefrLevel,
Status: "active",
}
row := s.db.QueryRowContext(ctx, `
INSERT INTO conversation_sessions (id, user_id, target_language, cefr_level, status)
VALUES ($1, $2, $3, $4, $5)
RETURNING created_at
`, session.ID, session.UserID, session.TargetLanguage, session.CEFRLevel, session.Status)
if err := row.Scan(&session.CreatedAt); err != nil {
return domain.ConversationSession{}, err
}
return session, nil
}
func (s *PostgresStore) SaveConversationTurn(ctx context.Context, turn domain.ConversationTurn) (domain.ConversationTurn, error) {
if turn.ID == "" {
turn.ID = NewID("trn")
}
row := s.db.QueryRowContext(ctx, `
INSERT INTO conversation_turns (id, session_id, speaker, text, attempt_id)
VALUES ($1, $2, $3, $4, NULLIF($5, ''))
RETURNING created_at
`, turn.ID, turn.SessionID, turn.Speaker, turn.Text, turn.AttemptID)
if err := row.Scan(&turn.CreatedAt); err != nil {
return domain.ConversationTurn{}, err
}
return turn, nil
}
func scanLanguage(scanner interface{ Scan(dest ...any) error }) (domain.LanguageProfile, error) {
var lang domain.LanguageProfile
var voicesRaw []byte
if err := scanner.Scan(
&lang.Code, &lang.DisplayName, &lang.AzureLocale, &lang.DefaultTTSVoice, &voicesRaw,
&lang.SupportsPronunciationAssessment, &lang.SupportsProsody,
); err != nil {
return domain.LanguageProfile{}, err
}
if err := json.Unmarshal(voicesRaw, &lang.Voices); err != nil {
return domain.LanguageProfile{}, err
}
return lang, nil
}
func scanAttempt(scanner interface{ Scan(dest ...any) error }) (domain.Attempt, error) {
var attempt domain.Attempt
var wordsRaw []byte
if err := scanner.Scan(
&attempt.ID, &attempt.UserID, &attempt.ExerciseID, &attempt.TargetLanguage, &attempt.RecognizedText,
&attempt.OverallScore, &attempt.AccuracyScore, &attempt.FluencyScore, &attempt.CompletenessScore, &attempt.ProsodyScore,
&wordsRaw, &attempt.TeacherFeedback, &attempt.CreatedAt,
); err != nil {
return domain.Attempt{}, err
}
if len(wordsRaw) > 0 {
_ = json.Unmarshal(wordsRaw, &attempt.WordScores)
}
return attempt, nil
}
func valueOr(value, fallback string) string {
if strings.TrimSpace(value) == "" {
return fallback
}
return value
}
const schemaSQL = `
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
ui_language TEXT NOT NULL DEFAULT 'de-DE',
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS learner_profiles (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
target_language TEXT NOT NULL,
cefr_level TEXT NOT NULL DEFAULT 'A1',
daily_goal_minutes INT NOT NULL DEFAULT 10,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (user_id, target_language)
);
CREATE TABLE IF NOT EXISTS language_profiles (
code TEXT PRIMARY KEY,
display_name TEXT NOT NULL,
azure_locale TEXT NOT NULL,
default_tts_voice TEXT NOT NULL,
voices_json JSONB NOT NULL DEFAULT '[]'::jsonb,
supports_pronunciation_assessment BOOLEAN NOT NULL DEFAULT true,
supports_prosody BOOLEAN NOT NULL DEFAULT true
);
CREATE TABLE IF NOT EXISTS lessons (
id TEXT PRIMARY KEY,
target_language TEXT NOT NULL,
cefr_level TEXT NOT NULL,
topic TEXT NOT NULL,
title TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS exercises (
id TEXT PRIMARY KEY,
lesson_id TEXT NOT NULL REFERENCES lessons(id) ON DELETE CASCADE,
target_language TEXT NOT NULL,
cefr_level TEXT NOT NULL,
type TEXT NOT NULL,
prompt_text TEXT NOT NULL,
target_text TEXT NOT NULL,
difficulty INT NOT NULL DEFAULT 1
);
CREATE TABLE IF NOT EXISTS attempts (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
exercise_id TEXT NOT NULL REFERENCES exercises(id) ON DELETE CASCADE,
target_language TEXT NOT NULL,
recognized_text TEXT NOT NULL,
overall_score DOUBLE PRECISION NOT NULL,
accuracy_score DOUBLE PRECISION NOT NULL,
fluency_score DOUBLE PRECISION NOT NULL,
completeness_score DOUBLE PRECISION NOT NULL,
prosody_score DOUBLE PRECISION NOT NULL,
word_scores_json JSONB NOT NULL DEFAULT '[]'::jsonb,
teacher_feedback TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS progress_events (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
target_language TEXT NOT NULL,
event_type TEXT NOT NULL,
payload_json JSONB NOT NULL DEFAULT '{}'::jsonb,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS conversation_sessions (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
target_language TEXT NOT NULL,
cefr_level TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'active',
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS conversation_turns (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL REFERENCES conversation_sessions(id) ON DELETE CASCADE,
speaker TEXT NOT NULL,
text TEXT NOT NULL,
attempt_id TEXT REFERENCES attempts(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_attempts_user_created ON attempts(user_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_exercises_language_level ON exercises(target_language, cefr_level);
`
var seedSQL = []string{
`INSERT INTO language_profiles (
code, display_name, azure_locale, default_tts_voice, voices_json,
supports_pronunciation_assessment, supports_prosody
) VALUES (
'en-US', 'English (United States)', 'en-US', 'en-US-JennyNeural',
'["en-US-JennyNeural", "en-US-GuyNeural", "en-US-AriaNeural"]'::jsonb,
true, true
) ON CONFLICT (code) DO UPDATE SET
display_name = EXCLUDED.display_name,
azure_locale = EXCLUDED.azure_locale,
default_tts_voice = EXCLUDED.default_tts_voice,
voices_json = EXCLUDED.voices_json`,
`INSERT INTO language_profiles (
code, display_name, azure_locale, default_tts_voice, voices_json,
supports_pronunciation_assessment, supports_prosody
) VALUES (
'es-ES', 'Spanish (Spain)', 'es-ES', 'es-ES-ElviraNeural',
'["es-ES-ElviraNeural", "es-ES-AlvaroNeural"]'::jsonb,
true, true
) ON CONFLICT (code) DO NOTHING`,
`INSERT INTO lessons (id, target_language, cefr_level, topic, title)
VALUES
('les_a1_intro', 'en-US', 'A1', 'introductions', 'Introduce yourself'),
('les_a1_cafe', 'en-US', 'A1', 'cafe', 'Order a coffee'),
('les_a1_numbers', 'en-US', 'A1', 'numbers', 'Numbers and names')
ON CONFLICT (id) DO UPDATE SET title = EXCLUDED.title`,
`INSERT INTO exercises (id, lesson_id, target_language, cefr_level, type, prompt_text, target_text, difficulty)
VALUES
('ex_a1_hello', 'les_a1_intro', 'en-US', 'A1', 'repeat_sentence', 'Sprich den Satz klar nach.', 'Hello, my name is Anna.', 1),
('ex_a1_from', 'les_a1_intro', 'en-US', 'A1', 'repeat_sentence', 'Achte auf den Rhythmus im Satz.', 'I am from Berlin.', 1),
('ex_a1_coffee', 'les_a1_cafe', 'en-US', 'A1', 'repeat_sentence', 'Sprich langsam und deutlich.', 'Can I have a coffee, please?', 2),
('ex_a1_water', 'les_a1_cafe', 'en-US', 'A1', 'repeat_sentence', 'Achte auf die Endlaute.', 'I would like some water.', 2),
('ex_a1_phone', 'les_a1_numbers', 'en-US', 'A1', 'repeat_sentence', 'Sprich jede Zahl einzeln sauber.', 'My phone number is five, two, nine.', 2)
ON CONFLICT (id) DO UPDATE SET
prompt_text = EXCLUDED.prompt_text,
target_text = EXCLUDED.target_text,
difficulty = EXCLUDED.difficulty`,
}
func DebugSQL(name string, err error) error {
if err == nil {
return nil
}
return fmt.Errorf("%s: %w", name, err)
}