Backend: - gemini/client.go: refactor to shared callGroq transport; add generateVisionContent using llama-3.2-11b-vision-preview model - gemini/recognition.go: RecognizeReceipt, RecognizeProducts, RecognizeDish (vision), ClassifyIngredient (text); shared parseJSON helper - ingredient/repository.go: add FuzzyMatch (wraps Search, returns best hit) - recognition/handler.go: POST /ai/recognize-receipt, /ai/recognize-products, /ai/recognize-dish; enrichItems with fuzzy match + AI classify fallback; parallel multi-image processing with deduplication - server.go + main.go: wire recognition handler under /ai routes Flutter: - pubspec.yaml: add image_picker ^1.1.0 - AndroidManifest.xml: add CAMERA and READ_EXTERNAL_STORAGE permissions - Info.plist: add NSCameraUsageDescription and NSPhotoLibraryUsageDescription - recognition_service.dart: RecognitionService wrapping /ai/* endpoints; RecognizedItem, ReceiptResult, DishResult models - scan_screen.dart: mode selector (receipt / products / dish / manual); image source picker; loading overlay; navigates to confirm or dish screen - recognition_confirm_screen.dart: editable list of recognized items; inline qty/unit editing; swipe-to-delete; batch-add to pantry - dish_result_screen.dart: dish name, KBZHU breakdown, similar dishes chips - app_router.dart: /scan, /scan/confirm, /scan/dish routes (no bottom nav) - products_screen.dart: FAB now shows bottom sheet with Manual / Scan options Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
225 lines
7.2 KiB
Go
225 lines
7.2 KiB
Go
package ingredient
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
// Repository handles persistence for ingredient_mappings.
|
|
type Repository struct {
|
|
pool *pgxpool.Pool
|
|
}
|
|
|
|
// NewRepository creates a new Repository.
|
|
func NewRepository(pool *pgxpool.Pool) *Repository {
|
|
return &Repository{pool: pool}
|
|
}
|
|
|
|
// Upsert inserts or updates an ingredient mapping.
|
|
// Conflict is resolved on spoonacular_id when set; otherwise a simple insert is done.
|
|
func (r *Repository) Upsert(ctx context.Context, m *IngredientMapping) (*IngredientMapping, error) {
|
|
query := `
|
|
INSERT INTO ingredient_mappings (
|
|
canonical_name, canonical_name_ru, spoonacular_id, aliases,
|
|
category, default_unit,
|
|
calories_per_100g, protein_per_100g, fat_per_100g, carbs_per_100g, fiber_per_100g,
|
|
storage_days
|
|
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
|
|
ON CONFLICT (spoonacular_id) DO UPDATE SET
|
|
canonical_name = EXCLUDED.canonical_name,
|
|
aliases = EXCLUDED.aliases,
|
|
category = EXCLUDED.category,
|
|
default_unit = EXCLUDED.default_unit,
|
|
calories_per_100g = EXCLUDED.calories_per_100g,
|
|
protein_per_100g = EXCLUDED.protein_per_100g,
|
|
fat_per_100g = EXCLUDED.fat_per_100g,
|
|
carbs_per_100g = EXCLUDED.carbs_per_100g,
|
|
fiber_per_100g = EXCLUDED.fiber_per_100g,
|
|
storage_days = EXCLUDED.storage_days,
|
|
updated_at = now()
|
|
RETURNING id, canonical_name, canonical_name_ru, spoonacular_id, aliases,
|
|
category, default_unit,
|
|
calories_per_100g, protein_per_100g, fat_per_100g, carbs_per_100g, fiber_per_100g,
|
|
storage_days, created_at, updated_at`
|
|
|
|
row := r.pool.QueryRow(ctx, query,
|
|
m.CanonicalName, m.CanonicalNameRu, m.SpoonacularID, m.Aliases,
|
|
m.Category, m.DefaultUnit,
|
|
m.CaloriesPer100g, m.ProteinPer100g, m.FatPer100g, m.CarbsPer100g, m.FiberPer100g,
|
|
m.StorageDays,
|
|
)
|
|
return scanMapping(row)
|
|
}
|
|
|
|
// GetBySpoonacularID returns an ingredient mapping by Spoonacular ID.
|
|
// Returns nil, nil if not found.
|
|
func (r *Repository) GetBySpoonacularID(ctx context.Context, id int) (*IngredientMapping, error) {
|
|
query := `
|
|
SELECT id, canonical_name, canonical_name_ru, spoonacular_id, aliases,
|
|
category, default_unit,
|
|
calories_per_100g, protein_per_100g, fat_per_100g, carbs_per_100g, fiber_per_100g,
|
|
storage_days, created_at, updated_at
|
|
FROM ingredient_mappings
|
|
WHERE spoonacular_id = $1`
|
|
|
|
row := r.pool.QueryRow(ctx, query, id)
|
|
m, err := scanMapping(row)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, nil
|
|
}
|
|
return m, err
|
|
}
|
|
|
|
// GetByID returns an ingredient mapping by UUID.
|
|
// Returns nil, nil if not found.
|
|
func (r *Repository) GetByID(ctx context.Context, id string) (*IngredientMapping, error) {
|
|
query := `
|
|
SELECT id, canonical_name, canonical_name_ru, spoonacular_id, aliases,
|
|
category, default_unit,
|
|
calories_per_100g, protein_per_100g, fat_per_100g, carbs_per_100g, fiber_per_100g,
|
|
storage_days, created_at, updated_at
|
|
FROM ingredient_mappings
|
|
WHERE id = $1`
|
|
|
|
row := r.pool.QueryRow(ctx, query, id)
|
|
m, err := scanMapping(row)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, nil
|
|
}
|
|
return m, err
|
|
}
|
|
|
|
// FuzzyMatch finds the single best matching ingredient mapping for a given name.
|
|
// Returns nil, nil when no match is found.
|
|
func (r *Repository) FuzzyMatch(ctx context.Context, name string) (*IngredientMapping, error) {
|
|
results, err := r.Search(ctx, name, 1)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(results) == 0 {
|
|
return nil, nil
|
|
}
|
|
return results[0], nil
|
|
}
|
|
|
|
// Search finds ingredient mappings matching the query string.
|
|
// Uses a three-level strategy: exact aliases match, ILIKE, and pg_trgm similarity.
|
|
func (r *Repository) Search(ctx context.Context, query string, limit int) ([]*IngredientMapping, error) {
|
|
if limit <= 0 {
|
|
limit = 10
|
|
}
|
|
q := `
|
|
SELECT id, canonical_name, canonical_name_ru, spoonacular_id, aliases,
|
|
category, default_unit,
|
|
calories_per_100g, protein_per_100g, fat_per_100g, carbs_per_100g, fiber_per_100g,
|
|
storage_days, created_at, updated_at
|
|
FROM ingredient_mappings
|
|
WHERE aliases @> to_jsonb(lower($1)::text)
|
|
OR canonical_name_ru ILIKE '%' || $1 || '%'
|
|
OR similarity(canonical_name_ru, $1) > 0.3
|
|
ORDER BY similarity(canonical_name_ru, $1) DESC
|
|
LIMIT $2`
|
|
|
|
rows, err := r.pool.Query(ctx, q, query, limit)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("search ingredient_mappings: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
return collectMappings(rows)
|
|
}
|
|
|
|
// Count returns the total number of ingredient mappings.
|
|
func (r *Repository) Count(ctx context.Context) (int, error) {
|
|
var n int
|
|
if err := r.pool.QueryRow(ctx, `SELECT count(*) FROM ingredient_mappings`).Scan(&n); err != nil {
|
|
return 0, fmt.Errorf("count ingredient_mappings: %w", err)
|
|
}
|
|
return n, nil
|
|
}
|
|
|
|
// ListUntranslated returns ingredients without a Russian name, ordered by id.
|
|
func (r *Repository) ListUntranslated(ctx context.Context, limit, offset int) ([]*IngredientMapping, error) {
|
|
query := `
|
|
SELECT id, canonical_name, canonical_name_ru, spoonacular_id, aliases,
|
|
category, default_unit,
|
|
calories_per_100g, protein_per_100g, fat_per_100g, carbs_per_100g, fiber_per_100g,
|
|
storage_days, created_at, updated_at
|
|
FROM ingredient_mappings
|
|
WHERE canonical_name_ru IS NULL
|
|
ORDER BY id
|
|
LIMIT $1 OFFSET $2`
|
|
|
|
rows, err := r.pool.Query(ctx, query, limit, offset)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list untranslated: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
return collectMappings(rows)
|
|
}
|
|
|
|
// UpdateTranslation saves the Russian name and adds Russian aliases.
|
|
func (r *Repository) UpdateTranslation(ctx context.Context, id, canonicalNameRu string, aliasesRu []string) error {
|
|
// Merge new aliases into existing JSONB array without duplicates
|
|
query := `
|
|
UPDATE ingredient_mappings SET
|
|
canonical_name_ru = $2,
|
|
aliases = (
|
|
SELECT jsonb_agg(DISTINCT elem)
|
|
FROM (
|
|
SELECT jsonb_array_elements(aliases) AS elem
|
|
UNION
|
|
SELECT to_jsonb(unnest) FROM unnest($3::text[]) AS unnest
|
|
) sub
|
|
),
|
|
updated_at = now()
|
|
WHERE id = $1`
|
|
|
|
if _, err := r.pool.Exec(ctx, query, id, canonicalNameRu, aliasesRu); err != nil {
|
|
return fmt.Errorf("update translation %s: %w", id, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// --- helpers ---
|
|
|
|
func scanMapping(row pgx.Row) (*IngredientMapping, error) {
|
|
var m IngredientMapping
|
|
var aliases []byte
|
|
|
|
err := row.Scan(
|
|
&m.ID, &m.CanonicalName, &m.CanonicalNameRu, &m.SpoonacularID, &aliases,
|
|
&m.Category, &m.DefaultUnit,
|
|
&m.CaloriesPer100g, &m.ProteinPer100g, &m.FatPer100g, &m.CarbsPer100g, &m.FiberPer100g,
|
|
&m.StorageDays, &m.CreatedAt, &m.UpdatedAt,
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
m.Aliases = json.RawMessage(aliases)
|
|
return &m, nil
|
|
}
|
|
|
|
func collectMappings(rows pgx.Rows) ([]*IngredientMapping, error) {
|
|
var result []*IngredientMapping
|
|
for rows.Next() {
|
|
var m IngredientMapping
|
|
var aliases []byte
|
|
if err := rows.Scan(
|
|
&m.ID, &m.CanonicalName, &m.CanonicalNameRu, &m.SpoonacularID, &aliases,
|
|
&m.Category, &m.DefaultUnit,
|
|
&m.CaloriesPer100g, &m.ProteinPer100g, &m.FatPer100g, &m.CarbsPer100g, &m.FiberPer100g,
|
|
&m.StorageDays, &m.CreatedAt, &m.UpdatedAt,
|
|
); err != nil {
|
|
return nil, fmt.Errorf("scan mapping: %w", err)
|
|
}
|
|
m.Aliases = json.RawMessage(aliases)
|
|
result = append(result, &m)
|
|
}
|
|
return result, rows.Err()
|
|
}
|