From 614c23eaed6c34fb1688aadfe61baecc9d1bad9d Mon Sep 17 00:00:00 2001 From: Eylul Seyitoglu Date: Fri, 23 Oct 2026 14:43:41 +0300 Subject: [PATCH 01/10] chore: remove unused files and course artifacts --- TASKS.md | 24 -- backend/DATABASE_SETUP.md | 71 ----- frontend/README.md | 36 --- frontend/tailwind.config.ts | 20 -- hf_mcp_tool/hf_requirements.txt | 2 - hf_mcp_tool/huggingface_mcp_server.py | 87 ------ hf_mcp_tool/requirements.txt | 0 scripts/PRD.md | 139 ---------- scripts/design.json | 375 -------------------------- 9 files changed, 754 deletions(-) delete mode 100644 TASKS.md delete mode 100644 backend/DATABASE_SETUP.md delete mode 100644 frontend/README.md delete mode 100644 frontend/tailwind.config.ts delete mode 100644 hf_mcp_tool/hf_requirements.txt delete mode 100644 hf_mcp_tool/huggingface_mcp_server.py delete mode 100644 hf_mcp_tool/requirements.txt delete mode 100644 scripts/PRD.md delete mode 100644 scripts/design.json diff --git a/TASKS.md b/TASKS.md deleted file mode 100644 index df5480d..0000000 --- a/TASKS.md +++ /dev/null @@ -1,24 +0,0 @@ -# Capstone Project Tasks - -## Faz 1: Fikir ve Planlama (Tamamlandı) -- [x] Problem tanımı ve fikir üretimi (PRD.md ile yapıldı). -- [x] Kullanıcı akışı ve teknoloji seçimi (PRD.md içinde tanımlandı). - -## Faz 2: Kodlama ve AI Entegrasyonu (Tamamlandı) -- [x] GitHub reposu kuruldu ve proje yapılandırıldı. -- [x] Temel özellik geliştirildi (Malzeme girişi -> AI Tarif çıktısı). -- [x] Google Gemini LLM entegrasyonu sağlandı. - -## Faz 3: Otomasyon ve Ajans Mantığı -- [ ] Tarifi analiz edip alışveriş listesi çıkaran bir otomasyon kur. -- [ ] LangChain veya benzeri bir kütüphane kullanarak daha yetenekli bir tarif 'Agent'ı oluştur (örneğin: tarif varyasyonları önerme). - -## Faz 4: RAG veya Fine-tuning Uygulaması -- [ ] Mevcut tarifleri saklamak için bir VectorDB entegrasyonu yap (Chroma, FAISS vb.). -- [ ] Kullanıcının malzemelerine en uygun tarifi VectorDB'den bulan bir RAG (Retrieval-Augmented Generation) sistemi kur. - -## Faz 5: Yayınlama ve Demo -- [ ] Frontend uygulamasını Vercel'e dağıt. -- [ ] Backend uygulamasını Railway'e dağıt. -- [ ] Proje için bir tanıtım sayfası (Landing Page) oluştur. -- [ ] Projenin demo videosunu veya GIF'ini hazırla. diff --git a/backend/DATABASE_SETUP.md b/backend/DATABASE_SETUP.md deleted file mode 100644 index fe5e07b..0000000 --- a/backend/DATABASE_SETUP.md +++ /dev/null @@ -1,71 +0,0 @@ -# Database Setup Guide - -## PostgreSQL Installation - -### Option 1: Install PostgreSQL Locally -1. Download PostgreSQL from: https://www.postgresql.org/download/ -2. Install with default settings -3. Remember the password you set for the `postgres` user - -### Option 2: Use Docker (Recommended) -```bash -# Run PostgreSQL in Docker -docker run --name recipe-db -e POSTGRES_PASSWORD=password -e POSTGRES_DB=recipe_db -p 5432:5432 -d postgres:15 -``` - -## Database Configuration - -1. Create a `.env` file in the backend directory: -```env -DATABASE_URL=postgresql://postgres:password@localhost:5432/recipe_db -API_V1_STR=/api/v1 -PROJECT_NAME=Recipe Recommendation API -BACKEND_CORS_ORIGINS=["http://localhost:3000","http://127.0.0.1:3000"] -``` - -2. Initialize the database: -```bash -cd backend -python init_db.py -``` - -## Database Schema - -The application creates the following tables: - -- **users** - User accounts for tracking queries -- **ingredients** - Available ingredients with popularity tracking -- **tags** - Recipe tags (vegetarian, quick, etc.) -- **recipes** - Generated recipes -- **recipe_instructions** - Step-by-step instructions -- **user_queries** - Track user search queries -- **recipe_ratings** - User ratings and feedback - -## Features Added - -✅ **Recipe Storage** - Save generated recipes to database -✅ **Ingredient Tracking** - Track popular ingredients -✅ **User Analytics** - Save user queries for insights -✅ **Query History** - Track what users search for -✅ **Popular Ingredients** - Show trending ingredients - -## Testing the Database - -1. Start the backend server: -```bash -uvicorn main:app --reload -``` - -2. Test the API endpoints: -- `POST /api/v1/users/create` - Create a user -- `POST /api/v1/recipes/recommend` - Get recipe (saves to DB) -- `GET /api/v1/ingredients/popular` - Get popular ingredients -- `GET /api/v1/ingredients/suggestions?query=onion` - Get suggestions - -## Next Steps - -After database setup, you can: -1. Add AI integration for real recipe generation -2. Implement user authentication -3. Add recipe rating system -4. Create analytics dashboard \ No newline at end of file diff --git a/frontend/README.md b/frontend/README.md deleted file mode 100644 index e215bc4..0000000 --- a/frontend/README.md +++ /dev/null @@ -1,36 +0,0 @@ -This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app). - -## Getting Started - -First, run the development server: - -```bash -npm run dev -# or -yarn dev -# or -pnpm dev -# or -bun dev -``` - -Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. - -You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. - -This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel. - -## Learn More - -To learn more about Next.js, take a look at the following resources: - -- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. -- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. - -You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome! - -## Deploy on Vercel - -The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. - -Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details. diff --git a/frontend/tailwind.config.ts b/frontend/tailwind.config.ts deleted file mode 100644 index e9a0944..0000000 --- a/frontend/tailwind.config.ts +++ /dev/null @@ -1,20 +0,0 @@ -import type { Config } from "tailwindcss"; - -const config: Config = { - content: [ - "./src/pages/**/*.{js,ts,jsx,tsx,mdx}", - "./src/components/**/*.{js,ts,jsx,tsx,mdx}", - "./src/app/**/*.{js,ts,jsx,tsx,mdx}", - ], - theme: { - extend: { - backgroundImage: { - "gradient-radial": "radial-gradient(var(--tw-gradient-stops))", - "gradient-conic": - "conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))", - }, - }, - }, - plugins: [], -}; -export default config; diff --git a/hf_mcp_tool/hf_requirements.txt b/hf_mcp_tool/hf_requirements.txt deleted file mode 100644 index 3ac85a4..0000000 --- a/hf_mcp_tool/hf_requirements.txt +++ /dev/null @@ -1,2 +0,0 @@ -flask -huggingface_hub diff --git a/hf_mcp_tool/huggingface_mcp_server.py b/hf_mcp_tool/huggingface_mcp_server.py deleted file mode 100644 index 012445b..0000000 --- a/hf_mcp_tool/huggingface_mcp_server.py +++ /dev/null @@ -1,87 +0,0 @@ -from flask import Flask, request, jsonify -from huggingface_hub import HfApi, hf_hub_url -import json - -app = Flask(__name__) -api = HfApi() - -def get_tool_metadata(): - return { - "mcp_version": "0.1", - "tools": [ - { - "name": "model_search", - "description": "Find Machine Learning models hosted on Hugging Face.", - "parameters": [ - {"name": "query", "type": "string", "description": "Search term."}, - {"name": "author", "type": "string", "description": "Organization or user who created the model."}, - {"name": "task", "type": "string", "description": "Model task type."}, - {"name": "sort", "type": "string", "description": "Sort order: downloads, likes, lastModified."}, - {"name": "limit", "type": "number", "description": "Maximum number of results to return."} - ] - }, - { - "name": "dataset_search", - "description": "Find Datasets hosted on the Hugging Face hub.", - "parameters": [ - {"name": "query", "type": "string", "description": "Search term."}, - {"name": "author", "type": "string", "description": "Organization or user who created the dataset."}, - {"name": "sort", "type": "string", "description": "Sort order: downloads, likes, lastModified."}, - {"name": "limit", "type": "number", "description": "Maximum number of results to return."} - ] - }, - { - "name": "space_search", - "description": "Find Hugging Face Spaces using semantic search.", - "parameters": [ - {"name": "query", "type": "string", "description": "Semantic Search Query."}, - {"name": "limit", "type": "number", "description": "Number of results to return."} - ] - } - ] - } - -@app.route('/mcp', methods=['GET']) -def mcp_schema(): - return jsonify(get_tool_metadata()) - -@app.route('/mcp/', methods=['POST']) -def execute_tool(tool_name): - params = request.get_json() - try: - if tool_name == "model_search": - result = api.list_models( - search=params.get("query"), - author=params.get("author"), - task=params.get("task"), - sort=params.get("sort"), - limit=int(params.get("limit", 10)) - ) - # Convert model objects to dicts for JSON serialization - result = [vars(model) for model in result] - elif tool_name == "dataset_search": - result = api.list_datasets( - search=params.get("query"), - author=params.get("author"), - sort=params.get("sort"), - limit=int(params.get("limit", 10)) - ) - result = [vars(dataset) for dataset in result] - elif tool_name == "space_search": - result = api.list_spaces( - search=params.get("query"), - limit=int(params.get("limit", 10)) - ) - result = [vars(space) for space in result] - else: - return jsonify({"error": "Tool not found"}), 404 - - # Clean up non-serializable fields if any - # A simple way is to convert everything to string, but a more robust solution is needed for production - return jsonify(json.loads(json.dumps(result, default=str))) - - except Exception as e: - return jsonify({"error": str(e)}), 500 - -if __name__ == '__main__': - app.run(port=5001, debug=True) diff --git a/hf_mcp_tool/requirements.txt b/hf_mcp_tool/requirements.txt deleted file mode 100644 index e69de29..0000000 diff --git a/scripts/PRD.md b/scripts/PRD.md deleted file mode 100644 index ca0f572..0000000 --- a/scripts/PRD.md +++ /dev/null @@ -1,139 +0,0 @@ -# Product Requirements Document (PRD) -**Proje:** AI-First Development Capstone Project – Recipe Recommendation App -**Versiyon:** 1.0 -**Hazırlayan:** Eylül -**Tarih:** 17 Ağustos 2025 - ---- - -## 1. Proje Özeti - -Bu proje, kullanıcının elindeki malzemeleri girerek yapabileceği tarifleri öneren bir yapay zekâ destekli uygulamadır. -Amaç, kullanıcıya hızlı, doğru ve kişiselleştirilmiş tarif önerileri sunarak yemek hazırlama sürecini kolaylaştırmaktır. - -Proje, capstone sürecinde ilk prototip olarak geliştirilecek ve ilerleyen dönemlerde kullanıcı hesabı yönetimi, sesli giriş, alışveriş listesi çıkarma gibi özellikler eklenebilecektir. - ---- - -## 2. Hedef Kullanıcı Kitlesi - -- Evde yemek yapan kullanıcılar -- Yemek planlamasını kolaylaştırmak isteyen kişiler -- Malzeme bazlı tarif önerisi arayan kullanıcılar - ---- - -## 3. Kullanıcı Akışı - -### 3.1 Ana Sayfa -- Kullanıcı uygulamaya giriş yapar ve malzeme listesi girmesi gerektiğini belirten sade bir ekran görür. - -### 3.2 Malzeme Girişi -- Kullanıcı elindeki malzemeleri metin olarak yazar ve “Gönder” butonuna tıklar. -- Gelecekte sesli giriş opsiyonu eklenebilir. - -### 3.3 Opsiyonel Filtre Seçimi -- Kullanıcı, tarif önerileri için isteğe bağlı filtreler seçebilir (ör. vejetaryen, düşük kalorili). - -### 3.4 AI Destekli Tarif Önerisi -- Backend, kullanıcıdan gelen malzeme listesini alır. -- Açık kaynak büyük dil modeli ile uygun tarifler üretilir ve frontend’e iletilir. - -### 3.5 Tarif Gösterimi -- Kullanıcıya önerilen tarif aşağıdaki bilgilerle gösterilir: - - Tarif adı - - Malzeme listesi - - Pişirme adımları - - Yaklaşık süre - -### 3.6 Yeni Sorgu veya Çıkış -- Kullanıcı yeni bir malzeme listesi girmek isterse süreç tekrarlanır veya uygulamadan çıkabilir. - -#### Akış Şeması (Metin) -[ Ana Sayfa ] -↓ -[ Malzeme Girişi ] -↓ -[ Opsiyonel: Filtre Seçimi ] -↓ -[ AI Destekli Tarif Önerisi ] -↓ -[ Tarif Gösterimi ] -↓ -[ Yeni Sorgu veya Çıkış ] - - ---- - -## 4. Temel Özellikler - -- Malzeme bazlı tarif önerisi -- AI destekli öneri sistemi (açık kaynak LLM kullanımı) -- Opsiyonel filtreleme (diyet tercihlerine göre) -- Tarif detaylarını gösterme (isim, malzemeler, adımlar, süre) -- Basit ve kullanıcı dostu arayüz - -**İlerleyen Dönemde Eklenebilecek Özellikler:** -- Kullanıcı hesabı / oturum yönetimi -- Tarif kaydetme ve paylaşma -- Haftalık yemek planı önerisi -- Sesli malzeme girişi -- Alışveriş listesi oluşturma - ---- - -## 5. Teknik Gereksinimler - -### 5.1 Backend -- Python 3.12 + FastAPI -- AI modeli entegrasyonu ve veri işleme - -### 5.2 Frontend -- Next.js (React tabanlı) -- Malzeme girişi, filtre seçimi ve tarif gösterimi - -### 5.3 Yapay Zekâ ve AI -- Açık kaynak büyük dil modeli -- Metin analizi ve tarif önerisi -- Tarif özetleme ve filtreleme - -### 5.4 Veritabanı -- SQLite (hafif ve kolay yönetilebilir) -- Kullanıcı sorguları ve tarif verilerinin depolanması - -### 5.5 Versiyon Kontrol ve Proje Yönetimi -- Git ve GitHub - -### 5.6 Dağıtım -- Frontend: Vercel -- Backend: Railway - -### 5.7 İleriki Dönem Planları -- Vektör tabanlı veri tabanı ile metin arama ve tavsiye sistemi -- Çok adımlı AI işlemleri ve agent mimarisi -- Sesli malzeme girişinin eklenmesi - ---- - -## 6. Başarı Kriterleri - -- Kullanıcı malzeme listesi girdiğinde, doğru ve anlamlı tarif önerisi alması -- Kullanıcı arayüzünün sade, hızlı ve kullanıcı dostu olması -- AI modeli ile öneri sürecinin güvenilir ve hatasız çalışması -- Prototip süresince temel akışın eksiksiz uygulanması - ---- - -## 7. Sınırlamalar - -- İlk prototip yalnızca metin tabanlı malzeme girişini destekler -- Kullanıcı hesabı ve kişiselleştirme özellikleri ilk sürümde yok -- AI önerileri, eğitim verisi ve model kapasitesi ile sınırlı - ---- - -## 8. Notlar - -- Projenin ilerleyen sürümlerinde kullanıcı deneyimini artıracak yeni özellikler eklenebilir. -- AI modelinin performansı ve doğruluğu düzenli olarak test edilmelidir. -- Cursor’da markdown formatında hazırlanmış bu PRD, hem geliştirme sürecinde rehber hem de paydaşlarla paylaşım için uygundur. diff --git a/scripts/design.json b/scripts/design.json deleted file mode 100644 index 37bb81a..0000000 --- a/scripts/design.json +++ /dev/null @@ -1,375 +0,0 @@ -{ - "theme": { - "name": "Food Dashboard", - "mode": "light", - "primaryFont": "Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif", - "secondaryFont": "Poppins, sans-serif" - }, - "colors": { - "primary": { - "50": "#fff7ed", - "100": "#ffedd5", - "200": "#fed7aa", - "300": "#fdba74", - "400": "#fb923c", - "500": "#f97316", - "600": "#ea580c", - "700": "#c2410c", - "800": "#9a3412", - "900": "#7c2d12" - }, - "secondary": { - "50": "#f0fdf4", - "100": "#dcfce7", - "200": "#bbf7d0", - "300": "#86efac", - "400": "#4ade80", - "500": "#22c55e", - "600": "#16a34a", - "700": "#15803d", - "800": "#166534", - "900": "#14532d" - }, - "accent": { - "50": "#fef3c7", - "100": "#fde68a", - "200": "#fcd34d", - "300": "#fbbf24", - "400": "#f59e0b", - "500": "#d97706", - "600": "#b45309", - "700": "#92400e", - "800": "#78350f", - "900": "#451a03" - }, - "neutral": { - "50": "#f9fafb", - "100": "#f3f4f6", - "200": "#e5e7eb", - "300": "#d1d5db", - "400": "#9ca3af", - "500": "#6b7280", - "600": "#4b5563", - "700": "#374151", - "800": "#1f2937", - "900": "#111827" - }, - "background": { - "primary": "#ffffff", - "secondary": "#f9fafb", - "tertiary": "#f3f4f6" - }, - "text": { - "primary": "#111827", - "secondary": "#4b5563", - "muted": "#6b7280", - "inverse": "#ffffff" - }, - "status": { - "success": "#22c55e", - "warning": "#f59e0b", - "error": "#ef4444", - "info": "#3b82f6" - } - }, - "typography": { - "h1": { - "fontSize": "2.5rem", - "fontWeight": "700", - "lineHeight": "1.2", - "letterSpacing": "-0.025em", - "color": "text.primary" - }, - "h2": { - "fontSize": "2rem", - "fontWeight": "600", - "lineHeight": "1.3", - "letterSpacing": "-0.025em", - "color": "text.primary" - }, - "h3": { - "fontSize": "1.5rem", - "fontWeight": "600", - "lineHeight": "1.4", - "color": "text.primary" - }, - "h4": { - "fontSize": "1.25rem", - "fontWeight": "600", - "lineHeight": "1.5", - "color": "text.primary" - }, - "body": { - "fontSize": "1rem", - "fontWeight": "400", - "lineHeight": "1.6", - "color": "text.secondary" - }, - "caption": { - "fontSize": "0.875rem", - "fontWeight": "500", - "lineHeight": "1.5", - "color": "text.muted" - }, - "small": { - "fontSize": "0.75rem", - "fontWeight": "400", - "lineHeight": "1.4", - "color": "text.muted" - } - }, - "spacing": { - "xs": "0.25rem", - "sm": "0.5rem", - "md": "1rem", - "lg": "1.5rem", - "xl": "2rem", - "2xl": "3rem", - "3xl": "4rem" - }, - "borderRadius": { - "none": "0", - "sm": "0.375rem", - "md": "0.5rem", - "lg": "0.75rem", - "xl": "1rem", - "2xl": "1.5rem", - "full": "9999px" - }, - "shadows": { - "sm": "0 1px 2px 0 rgba(0, 0, 0, 0.05)", - "md": "0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)", - "lg": "0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)", - "xl": "0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)" - }, - "components": { - "card": { - "background": "background.primary", - "borderRadius": "lg", - "padding": "lg", - "boxShadow": "md", - "border": "1px solid #e5e7eb" - }, - "button": { - "primary": { - "background": "primary.500", - "color": "text.inverse", - "borderRadius": "md", - "padding": "sm lg", - "fontWeight": "500", - "hover": { - "background": "primary.600" - } - }, - "secondary": { - "background": "neutral.100", - "color": "text.primary", - "borderRadius": "md", - "padding": "sm lg", - "fontWeight": "500", - "hover": { - "background": "neutral.200" - } - }, - "outline": { - "background": "transparent", - "color": "primary.500", - "border": "1px solid", - "borderColor": "primary.500", - "borderRadius": "md", - "padding": "sm lg", - "fontWeight": "500", - "hover": { - "background": "primary.50" - } - } - }, - "input": { - "background": "background.primary", - "border": "1px solid #d1d5db", - "borderRadius": "md", - "padding": "sm md", - "fontSize": "body.fontSize", - "focus": { - "borderColor": "primary.500", - "outline": "2px solid rgba(249, 115, 22, 0.2)" - } - }, - "navbar": { - "background": "background.primary", - "borderBottom": "1px solid #e5e7eb", - "padding": "sm lg", - "height": "4rem" - }, - "sidebar": { - "background": "background.secondary", - "width": "16rem", - "padding": "lg md" - }, - "badge": { - "success": { - "background": "secondary.100", - "color": "secondary.700", - "borderRadius": "full", - "padding": "xs sm", - "fontSize": "small.fontSize", - "fontWeight": "500" - }, - "warning": { - "background": "accent.100", - "color": "accent.700", - "borderRadius": "full", - "padding": "xs sm", - "fontSize": "small.fontSize", - "fontWeight": "500" - }, - "error": { - "background": "#fef2f2", - "color": "#991b1b", - "borderRadius": "full", - "padding": "xs sm", - "fontSize": "small.fontSize", - "fontWeight": "500" - } - }, - "progressBar": { - "background": "neutral.200", - "fill": "primary.500", - "height": "0.5rem", - "borderRadius": "full" - }, - "tooltip": { - "background": "neutral.800", - "color": "text.inverse", - "borderRadius": "md", - "padding": "xs sm", - "fontSize": "small.fontSize", - "boxShadow": "lg" - }, - "modal": { - "background": "background.primary", - "borderRadius": "xl", - "padding": "xl", - "boxShadow": "xl", - "overlay": "rgba(0, 0, 0, 0.5)" - } - }, - "icons": { - "size": { - "xs": "1rem", - "sm": "1.25rem", - "md": "1.5rem", - "lg": "2rem", - "xl": "2.5rem" - }, - "library": "lucide-react", - "common": { - "home": "Home", - "user": "User", - "settings": "Settings", - "search": "Search", - "menu": "Menu", - "close": "X", - "check": "Check", - "heart": "Heart", - "star": "Star", - "calendar": "Calendar", - "clock": "Clock", - "trending": "TrendingUp", - "activity": "Activity", - "utensils": "Utensils", - "chef": "ChefHat", - "apple": "Apple", - "coffee": "Coffee", - "pizza": "Pizza", - "bookmark": "Bookmark", - "share": "Share2", - "filter": "Filter", - "sort": "ArrowUpDown" - } - }, - "layout": { - "container": { - "maxWidth": "1200px", - "margin": "0 auto", - "padding": "0 lg" - }, - "grid": { - "columns": { - "mobile": 1, - "tablet": 2, - "desktop": 3, - "wide": 4 - }, - "gap": "lg" - } - }, - "breakpoints": { - "mobile": "480px", - "tablet": "768px", - "desktop": "1024px", - "wide": "1280px" - }, - "animations": { - "transition": { - "fast": "150ms ease-in-out", - "normal": "300ms ease-in-out", - "slow": "500ms ease-in-out" - }, - "hover": { - "scale": "1.02", - "transition": "transform 150ms ease-in-out" - }, - "fadeIn": { - "keyframes": "fadeIn 300ms ease-in-out", - "from": { "opacity": 0, "transform": "translateY(10px)" }, - "to": { "opacity": 1, "transform": "translateY(0)" } - } - }, - "foodTheme": { - "categories": { - "healthy": { - "color": "secondary.500", - "icon": "Apple", - "background": "secondary.50" - }, - "comfort": { - "color": "accent.500", - "icon": "Coffee", - "background": "accent.50" - }, - "gourmet": { - "color": "primary.500", - "icon": "ChefHat", - "background": "primary.50" - }, - "quick": { - "color": "status.info", - "icon": "Clock", - "background": "#eff6ff" - } - }, - "nutritionColors": { - "calories": "#f97316", - "protein": "#22c55e", - "carbs": "#3b82f6", - "fat": "#f59e0b", - "fiber": "#8b5cf6", - "sugar": "#ef4444" - }, - "difficultyLevels": { - "easy": { - "color": "secondary.500", - "background": "secondary.100" - }, - "medium": { - "color": "accent.500", - "background": "accent.100" - }, - "hard": { - "color": "primary.500", - "background": "primary.100" - } - } - } - } \ No newline at end of file From 799e8a7a8178273cf493ee731a3492c1ee1c07a0 Mon Sep 17 00:00:00 2001 From: Eylul Seyitoglu Date: Fri, 23 Oct 2026 15:06:38 +0300 Subject: [PATCH 02/10] fix(backend): load .env reliably and make settings configurable --- backend/.env.example | 7 ++++++ backend/app/core/config.py | 48 +++++++++++++++++++----------------- backend/app/core/database.py | 13 +++++----- backend/main.py | 15 +++++------ 4 files changed, 46 insertions(+), 37 deletions(-) create mode 100644 backend/.env.example diff --git a/backend/.env.example b/backend/.env.example new file mode 100644 index 0000000..e488c2b --- /dev/null +++ b/backend/.env.example @@ -0,0 +1,7 @@ +# Get a key at https://aistudio.google.com/apikey +GOOGLE_API_KEY= + +# Optional overrides +# GEMINI_MODEL=gemini-2.5-flash +# DATABASE_URL=sqlite:///./cookable.db +# CORS_ORIGINS=http://localhost:3000,http://127.0.0.1:3000 diff --git a/backend/app/core/config.py b/backend/app/core/config.py index 1f9ba29..c0d4225 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -1,30 +1,32 @@ import os -from dotenv import load_dotenv from pathlib import Path +from dotenv import load_dotenv + +BACKEND_DIR = Path(__file__).resolve().parents[2] + +# Load backend/.env regardless of the working directory the server is started from +load_dotenv(BACKEND_DIR / ".env") + + +def _split_csv(value: str) -> list[str]: + return [item.strip() for item in value.split(",") if item.strip()] -# Explicitly load the .env file from the 'backend' directory -# This makes the path independent of where the script is run from. -env_path = Path('.') / 'backend' / '.env' -load_dotenv(dotenv_path=env_path) class Settings: + PROJECT_NAME: str = "Cookable API" + API_V1_STR: str = "/api/v1" + # Database settings - DATABASE_URL: str = os.getenv( - "DATABASE_URL", - "sqlite:///./recipe.db" # Changed from PostgreSQL to SQLite + DATABASE_URL: str = os.getenv("DATABASE_URL", f"sqlite:///{BACKEND_DIR / 'cookable.db'}") + + # Google Gemini settings + GOOGLE_API_KEY: str | None = os.getenv("GOOGLE_API_KEY") + GEMINI_MODEL: str = os.getenv("GEMINI_MODEL", "gemini-2.5-flash") + + # CORS settings (comma-separated list of allowed origins) + CORS_ORIGINS: list[str] = _split_csv( + os.getenv("CORS_ORIGINS", "http://localhost:3000,http://127.0.0.1:3000") ) - - # API settings - API_V1_STR: str = "/api/v1" - PROJECT_NAME: str = "Recipe Recommendation API" - - # Google AI API Key - GOOGLE_API_KEY: str = os.getenv("GOOGLE_API_KEY") - - # CORS settings - BACKEND_CORS_ORIGINS: list = [ - "http://localhost:3000", - "http://127.0.0.1:3000", - ] - -settings = Settings() \ No newline at end of file + + +settings = Settings() diff --git a/backend/app/core/database.py b/backend/app/core/database.py index a3dd628..576bc20 100644 --- a/backend/app/core/database.py +++ b/backend/app/core/database.py @@ -1,12 +1,11 @@ from sqlalchemy import create_engine -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import sessionmaker +from sqlalchemy.orm import declarative_base, sessionmaker from app.core.config import settings -# For SQLite, we need to add connect_args -engine = create_engine( - settings.DATABASE_URL, connect_args={"check_same_thread": False} -) +# SQLite needs check_same_thread disabled because FastAPI may use the +# session from a different thread than the one that created it +connect_args = {"check_same_thread": False} if settings.DATABASE_URL.startswith("sqlite") else {} +engine = create_engine(settings.DATABASE_URL, connect_args=connect_args) # Create SessionLocal class SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) @@ -20,4 +19,4 @@ def get_db(): try: yield db finally: - db.close() \ No newline at end of file + db.close() diff --git a/backend/main.py b/backend/main.py index 7521ccb..7b4a9b7 100644 --- a/backend/main.py +++ b/backend/main.py @@ -1,6 +1,7 @@ from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from app.api.routes import router +from app.core.config import settings from app.core.database import engine from app.models import database_models @@ -8,31 +9,31 @@ database_models.Base.metadata.create_all(bind=engine) app = FastAPI( - title="Recipe Recommendation API", - description="AI-powered recipe recommendation based on available ingredients", + title=settings.PROJECT_NAME, + description="AI-powered recipe recommendations based on the ingredients you already have", version="1.0.0" ) # CORS middleware for frontend integration app.add_middleware( CORSMiddleware, - allow_origins=["http://localhost:3000", "http://127.0.0.1:3000"], # Next.js default + allow_origins=settings.CORS_ORIGINS, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Include API routes -app.include_router(router, prefix="/api/v1") +app.include_router(router, prefix=settings.API_V1_STR) @app.get("/") async def root(): - return {"message": "Recipe Recommendation API is running!"} + return {"message": "Cookable API is running!", "docs": "/docs"} @app.get("/health") async def health_check(): - return {"status": "healthy", "service": "recipe-recommendation-api"} + return {"status": "healthy", "service": "cookable-api"} if __name__ == "__main__": import uvicorn - uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file + uvicorn.run(app, host="0.0.0.0", port=8000) From 21f06c10f2b6917ca6a7640d1d616c6d628a4edd Mon Sep 17 00:00:00 2001 From: Eylul Seyitoglu Date: Fri, 23 Oct 2026 15:10:31 +0300 Subject: [PATCH 03/10] refactor(backend): use Gemini structured output for recipe generation --- backend/app/api/routes.py | 84 ++++---- backend/app/models/recipe.py | 37 ++-- backend/app/services/recipe_service.py | 276 ++++++++++--------------- backend/requirements.txt | 17 +- 4 files changed, 175 insertions(+), 239 deletions(-) diff --git a/backend/app/api/routes.py b/backend/app/api/routes.py index 2efe18d..a1a8cbc 100644 --- a/backend/app/api/routes.py +++ b/backend/app/api/routes.py @@ -1,64 +1,58 @@ -from fastapi import APIRouter, HTTPException, Depends -from pydantic import BaseModel +from fastapi import APIRouter, HTTPException, Depends, Query +from pydantic import BaseModel, Field from typing import List, Optional from sqlalchemy.orm import Session -from app.services.recipe_service import RecipeService +from app.models.recipe import Recipe +from app.services.recipe_service import RecipeService, LLMConfigurationError, RecipeGenerationError from app.core.database import get_db from app.services.database_service import DatabaseService router = APIRouter() class IngredientRequest(BaseModel): - ingredients: List[str] + ingredients: List[str] = Field(min_length=1, max_length=30) dietary_preferences: Optional[List[str]] = None - max_cooking_time: Optional[int] = None + max_cooking_time: Optional[int] = Field(default=None, gt=0, le=600) allow_external_ingredients: bool = False -class RecipeResponse(BaseModel): - title: str - ingredients: List[str] - instructions: List[str] - cooking_time: int - difficulty: str - servings: int - tags: List[str] - shopping_list: Optional[List[str]] = None - class UserCreateResponse(BaseModel): user_id: int message: str -@router.post("/recipes/recommend", response_model=RecipeResponse) +def get_recipe_service(db: Session = Depends(get_db)) -> RecipeService: + return RecipeService(db) + +@router.post("/recipes/recommend", response_model=Recipe) async def recommend_recipe( request: IngredientRequest, - db: Session = Depends(get_db) + recipe_service: RecipeService = Depends(get_recipe_service) ): """ Get recipe recommendations based on available ingredients """ + ingredients = [i.strip().lower() for i in request.ingredients if i.strip()] + if not ingredients: + raise HTTPException(status_code=422, detail="Please provide at least one ingredient.") + try: - recipe_service = RecipeService(db) - recipe = await recipe_service.get_recipe_recommendation( - ingredients=request.ingredients, + return await recipe_service.get_recipe_recommendation( + ingredients=ingredients, dietary_preferences=request.dietary_preferences, max_cooking_time=request.max_cooking_time, allow_external_ingredients=request.allow_external_ingredients ) - return recipe - except Exception as e: - raise HTTPException(status_code=500, detail=f"Error generating recipe: {str(e)}") + except LLMConfigurationError as e: + raise HTTPException(status_code=503, detail=str(e)) + except RecipeGenerationError as e: + raise HTTPException(status_code=502, detail=str(e)) @router.post("/users/create", response_model=UserCreateResponse) async def create_user(db: Session = Depends(get_db)): """ Create a new user for tracking queries """ - try: - db_service = DatabaseService(db) - user = db_service.create_user() - return UserCreateResponse(user_id=user.id, message="User created successfully") - except Exception as e: - raise HTTPException(status_code=500, detail=f"Error creating user: {str(e)}") + user = DatabaseService(db).create_user() + return UserCreateResponse(user_id=user.id, message="User created successfully") @router.get("/recipes/health") async def recipe_service_health(): @@ -69,35 +63,27 @@ async def recipe_service_health(): @router.get("/ingredients/suggestions") async def get_ingredient_suggestions( - query: str, - db: Session = Depends(get_db) + query: str = Query(min_length=1), + recipe_service: RecipeService = Depends(get_recipe_service) ): """ Get ingredient suggestions based on partial input """ - try: - recipe_service = RecipeService(db) - suggestions = await recipe_service.get_ingredient_suggestions(query) - return {"suggestions": suggestions} - except Exception as e: - raise HTTPException(status_code=500, detail=f"Error getting suggestions: {str(e)}") + suggestions = await recipe_service.get_ingredient_suggestions(query) + return {"suggestions": suggestions} @router.get("/ingredients/popular") async def get_popular_ingredients( - limit: int = 10, + limit: int = Query(default=10, ge=1, le=100), db: Session = Depends(get_db) ): """ Get most popular ingredients """ - try: - db_service = DatabaseService(db) - popular_ingredients = db_service.get_popular_ingredients(limit) - return { - "ingredients": [ - {"name": ingredient.name, "popularity": ingredient.popularity_count} - for ingredient in popular_ingredients - ] - } - except Exception as e: - raise HTTPException(status_code=500, detail=f"Error getting popular ingredients: {str(e)}") \ No newline at end of file + popular_ingredients = DatabaseService(db).get_popular_ingredients(limit) + return { + "ingredients": [ + {"name": ingredient.name, "popularity": ingredient.popularity_count} + for ingredient in popular_ingredients + ] + } diff --git a/backend/app/models/recipe.py b/backend/app/models/recipe.py index d27c332..0e065c9 100644 --- a/backend/app/models/recipe.py +++ b/backend/app/models/recipe.py @@ -1,18 +1,25 @@ -from pydantic import BaseModel +from pydantic import BaseModel, ConfigDict, Field from typing import List, Optional -class Recipe(BaseModel): - title: str - ingredients: List[str] - instructions: List[str] - cooking_time: int # in minutes - difficulty: str # Easy, Medium, Hard - servings: int - tags: List[str] # e.g., ["vegetarian", "quick", "pasta"] +class GeneratedRecipe(BaseModel): + """Recipe fields produced by the LLM.""" + title: str = Field(description="The name of the recipe") + ingredients: List[str] = Field(description="All ingredients required, including quantities") + instructions: List[str] = Field(description="Step-by-step preparation instructions") + cooking_time: int = Field(description="Total cooking time in minutes") + difficulty: str = Field(description="Difficulty level: Easy, Medium or Hard") + servings: int = Field(description="How many people the recipe serves") + tags: List[str] = Field(description='Relevant tags, e.g. "vegetarian", "quick", "dinner"') + +class ShoppingList(BaseModel): + """Ingredients the user still needs to buy.""" + shopping_list: List[str] = Field(description="Recipe ingredients the user does not have, without quantities") + +class Recipe(GeneratedRecipe): shopping_list: Optional[List[str]] = None - - class Config: - json_schema_extra = { + + model_config = ConfigDict( + json_schema_extra={ "example": { "title": "Pasta with Tomato Sauce", "ingredients": [ @@ -35,6 +42,8 @@ class Config: "cooking_time": 20, "difficulty": "Easy", "servings": 2, - "tags": ["pasta", "vegetarian", "quick"] + "tags": ["pasta", "vegetarian", "quick"], + "shopping_list": [] } - } \ No newline at end of file + } + ) diff --git a/backend/app/services/recipe_service.py b/backend/app/services/recipe_service.py index 41597e4..ee7f48d 100644 --- a/backend/app/services/recipe_service.py +++ b/backend/app/services/recipe_service.py @@ -1,43 +1,50 @@ -import asyncio -import json -import os -from typing import List, Optional, Dict, Any +import logging +from functools import lru_cache +from typing import List, Optional from sqlalchemy.orm import Session -from app.models.recipe import Recipe +from langchain_core.language_models import BaseChatModel +from langchain_google_genai import ChatGoogleGenerativeAI +from app.models.recipe import GeneratedRecipe, Recipe, ShoppingList from app.services.database_service import DatabaseService from app.core.config import settings -# --- Gemini Integration --- -from langchain_google_genai import ChatGoogleGenerativeAI +logger = logging.getLogger(__name__) + +class LLMConfigurationError(RuntimeError): + """Raised when the LLM cannot be set up (e.g. missing API key).""" + +class RecipeGenerationError(RuntimeError): + """Raised when the LLM fails to produce a usable recipe.""" + +@lru_cache +def get_llm() -> BaseChatModel: + """Create the Gemini chat model once and reuse it across requests.""" + if not settings.GOOGLE_API_KEY: + raise LLMConfigurationError("GOOGLE_API_KEY is not set. Add it to backend/.env.") + return ChatGoogleGenerativeAI( + model=settings.GEMINI_MODEL, + temperature=0.7, + google_api_key=settings.GOOGLE_API_KEY, + ) class RecipeService: - def __init__(self, db: Session = None): - self.db = db + def __init__(self, db: Optional[Session] = None, llm: Optional[BaseChatModel] = None): self.db_service = DatabaseService(db) if db else None - - print("--- Initializing RecipeService ---") - if not settings.GOOGLE_API_KEY: - print("!!! FATAL ERROR: GOOGLE_API_KEY is not being read from settings. Check your .env file and config.py.") - raise ValueError("GOOGLE_API_KEY environment variable not set.") - - print(f"Found GOOGLE_API_KEY, starting with: '{settings.GOOGLE_API_KEY[:5]}...'") + self._llm = llm - try: - # Initialize the Google Gemini model - self.llm = ChatGoogleGenerativeAI(model="gemini-1.5-flash", temperature=0.7, google_api_key=settings.GOOGLE_API_KEY) - print("--- Google Gemini Model Initialized SUCCESSFULLY ---") - except Exception as e: - print(f"!!! FATAL ERROR: FAILED to initialize Google Gemini Model !!!") - print(f"The error is: {e}") - print("This usually means the API key is invalid or the 'Generative Language API' is not enabled in your Google Cloud project.") - raise - self.common_ingredients = [ "onion", "garlic", "tomato", "potato", "carrot", "bell pepper", "chicken", "beef", "pork", "fish", "rice", "pasta", "bread", "egg", "milk", "cheese", "butter", "olive oil", "salt", "pepper" ] - + + @property + def llm(self) -> BaseChatModel: + # Resolved lazily so endpoints that don't need the LLM work without an API key + if self._llm is None: + self._llm = get_llm() + return self._llm + def _build_recipe_prompt( self, ingredients: List[str], @@ -46,39 +53,33 @@ def _build_recipe_prompt( allow_external_ingredients: bool ) -> str: """Helper function to build the prompt for the LLM.""" - - ingredients_str = ", ".join(ingredients) - prompt = f""" -You are a creative chef. Generate a single, delicious recipe based on the following ingredients: {ingredients_str}. -""" - - if not allow_external_ingredients: - prompt += "\nYou MUST ONLY use the ingredients provided. Do not suggest any extra ingredients that are not on the list." - else: - prompt += "\nYou can suggest a recipe that requires a few extra simple ingredients if it makes the dish significantly better. Assume the user has basic pantry staples like salt, pepper, and oil." + lines = [ + "You are a creative chef. Generate a single, delicious recipe based on " + f"the following ingredients: {', '.join(ingredients)}.", + ] - prompt += "\nPlease adhere to these constraints:\n" + if allow_external_ingredients: + lines.append( + "You can suggest a recipe that requires a few extra simple ingredients if it makes " + "the dish significantly better. Assume the user has basic pantry staples like salt, " + "pepper, and oil." + ) + else: + lines.append( + "You MUST ONLY use the ingredients provided. Do not suggest any extra ingredients " + "that are not on the list." + ) + constraints = [] if dietary_preferences: - preferences_str = ", ".join(dietary_preferences) - prompt += f"- Dietary Preferences: The recipe must be suitable for {preferences_str}.\\n" - + constraints.append(f"- Dietary preferences: the recipe must be suitable for {', '.join(dietary_preferences)}.") if max_cooking_time: - prompt += f"- Maximum Cooking Time: The total cooking time should not exceed {max_cooking_time} minutes.\\n" - - prompt += """ -Your response MUST be a single, valid JSON object with the following exact keys and value types: -- "title": (string) The name of the recipe. -- "ingredients": (list of strings) A list of all ingredients required, including quantities. -- "instructions": (list of strings) Step-by-step instructions for preparing the dish. -- "cooking_time": (integer) The total cooking time in minutes. -- "difficulty": (string) The difficulty level (e.g., "Easy", "Medium", "Hard"). -- "servings": (integer) How many people the recipe serves. -- "tags": (list of strings) Relevant tags for the recipe (e.g., "vegetarian", "quick", "dinner"). - -Do not include any text, explanation, or markdown formatting outside of the JSON object. -""" - return prompt.strip() + constraints.append(f"- Maximum cooking time: the total cooking time must not exceed {max_cooking_time} minutes.") + if constraints: + lines.append("Please adhere to these constraints:") + lines.extend(constraints) + + return "\n".join(lines) def _build_shopping_list_prompt( self, @@ -86,25 +87,18 @@ def _build_shopping_list_prompt( recipe_ingredients: List[str] ) -> str: """Helper function to build the shopping list prompt.""" - user_ingredients_str = ", ".join(user_ingredients) - recipe_ingredients_str = ", ".join(recipe_ingredients) - - prompt = f""" - A user has the following ingredients: {user_ingredients_str}. - A recipe requires these ingredients: {recipe_ingredients_str}. - - Compare the two lists and generate a shopping list of ingredients the user needs to buy. - The shopping list should only include items from the recipe that the user does not have. - - If the user has 'chicken', and the recipe needs '1 lb boneless, skinless chicken breasts', consider it as available. General terms match specific ones. - - Do not include quantities in the final list. - - If the user has all the ingredients, return an empty list. - - Your response MUST be a single, valid JSON object with a single key "shopping_list" which contains a list of strings. - Example: {{"shopping_list": ["boneless, skinless chicken breasts", "olive oil", "black pepper"]}} - - Do not include any text, explanation, or markdown formatting outside of the JSON object. - """ - return prompt.strip() + return "\n".join([ + f"A user has the following ingredients: {', '.join(user_ingredients)}.", + f"A recipe requires these ingredients: {', '.join(recipe_ingredients)}.", + "", + "Compare the two lists and generate a shopping list of ingredients the user needs to buy.", + "The shopping list should only include items from the recipe that the user does not have.", + "- If the user has 'chicken' and the recipe needs '1 lb boneless, skinless chicken breasts', " + "consider it available. General terms match specific ones.", + "- Assume basic pantry staples (salt, pepper, oil, water) are available.", + "- Do not include quantities in the final list.", + "- If the user has all the ingredients, return an empty list.", + ]) async def _generate_shopping_list( self, @@ -117,21 +111,16 @@ async def _generate_shopping_list( prompt = self._build_shopping_list_prompt(user_ingredients, recipe_ingredients) try: - llm_response = await self.llm.ainvoke(prompt) - response_content = llm_response.content - - if response_content.strip().startswith("```json"): - response_content = response_content.strip()[7:-4].strip() - - data = json.loads(response_content) - return data.get("shopping_list", []) - except (json.JSONDecodeError, KeyError): - # If parsing fails, return an empty list as a fallback + result = await self.llm.with_structured_output(ShoppingList).ainvoke(prompt) + return result.shopping_list + except Exception: + # The recipe is still useful without a shopping list, so don't fail the request + logger.exception("Failed to generate shopping list") return [] async def get_recipe_recommendation( - self, - ingredients: List[str], + self, + ingredients: List[str], dietary_preferences: Optional[List[str]] = None, max_cooking_time: Optional[int] = None, allow_external_ingredients: bool = False, @@ -140,10 +129,36 @@ async def get_recipe_recommendation( """ Generate a recipe recommendation based on available ingredients using Google Gemini. """ + prompt =self._build_recipe_prompt(ingredients, dietary_preferences, max_cooking_time, allow_external_ingredients) + logger.debug("Recipe prompt:\n%s", prompt) + + try: + generated = await self.llm.with_structured_output(GeneratedRecipe).ainvoke(prompt) + except LLMConfigurationError: + raise + except Exception as e: + logger.exception("LLM recipe generation failed") + raise RecipeGenerationError("Failed to generate a valid recipe from the AI model.") from e + + if generated is None: + raise RecipeGenerationError("The AI model returned an empty response.") + + recipe = Recipe(**generated.model_dump()) + + # Generate shopping list only if external ingredients are allowed + if allow_external_ingredients: + recipe.shopping_list = await self._generate_shopping_list( + user_ingredients=ingredients, + recipe_ingredients=recipe.ingredients + ) + else: + recipe.shopping_list = [] + + # Only record usage once a recipe was actually generated if self.db_service: for ingredient in ingredients: self.db_service.increment_ingredient_popularity(ingredient) - + if user_id: self.db_service.save_user_query( user_id=user_id, @@ -151,99 +166,28 @@ async def get_recipe_recommendation( dietary_preferences=dietary_preferences, max_cooking_time=max_cooking_time ) - - # Construct the prompt for Gemini - prompt = self._build_recipe_prompt(ingredients, dietary_preferences, max_cooking_time, allow_external_ingredients) - print("--- PROMPT SENT TO GEMINI ---") - print(prompt) - print("-----------------------------") - - try: - # Invoke the LLM asynchronously - llm_response = await self.llm.ainvoke(prompt) - response_content = llm_response.content - - print("--- RAW RESPONSE FROM GEMINI ---") - print(response_content) - print("--------------------------------") - - # Clean up the response if it's wrapped in a markdown code block - if response_content.strip().startswith("```json"): - response_content = response_content.strip()[7:-4].strip() - - recipe_data = json.loads(response_content) - - # Create a Recipe Pydantic model instance - recipe = Recipe(**recipe_data) - - # Generate shopping list only if external ingredients are allowed - if allow_external_ingredients: - shopping_list = await self._generate_shopping_list( - user_ingredients=ingredients, - recipe_ingredients=recipe.ingredients - ) - recipe.shopping_list = shopping_list - else: - recipe.shopping_list = [] - - except (json.JSONDecodeError, KeyError, TypeError) as e: - print(f"!!! FAILED TO PARSE LLM RESPONSE !!!") - print(f"Error: {e}") - print(f"Original non-JSON response was: {response_content}") - raise ValueError("Failed to generate a valid recipe from the AI model.") - - if self.db_service: + self.db_service.create_recipe(recipe) - + return recipe - + async def get_ingredient_suggestions(self, query: str) -> List[str]: """ Get ingredient suggestions based on partial input """ query_lower = query.lower() - + # If database is available, get popular ingredients if self.db_service: - popular_ingredients = self.db_service.get_popular_ingredients(10) + popular_ingredients = self.db_service.get_popular_ingredients(50) suggestions = [ingredient.name for ingredient in popular_ingredients] else: suggestions = self.common_ingredients - + # Filter by query filtered_suggestions = [ ingredient for ingredient in suggestions if query_lower in ingredient.lower() ] - + return filtered_suggestions[:10] # Limit to 10 suggestions - - def _filter_by_dietary_preferences( - self, - recipe: Recipe, - preferences: List[str] - ) -> bool: - """ - Filter recipe based on dietary preferences - """ - if not preferences: - return True - - recipe_tags = [tag.lower() for tag in recipe.tags] - - for preference in preferences: - preference_lower = preference.lower() - if preference_lower in recipe_tags: - return True - - return False - - def _filter_by_cooking_time( - self, - recipe: Recipe, - max_time: int - ) -> bool: - """ - Filter recipe based on maximum cooking time - """ - return recipe.cooking_time <= max_time \ No newline at end of file diff --git a/backend/requirements.txt b/backend/requirements.txt index a361f7b..404fa61 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -1,10 +1,7 @@ -fastapi -uvicorn -pydantic -python-dotenv -sqlalchemy -psycopg2-binary -langgraph -langchain-google-genai -google-generativeai -langchain \ No newline at end of file +fastapi>=0.115 +uvicorn[standard]>=0.30 +pydantic>=2.7 +python-dotenv>=1.0 +sqlalchemy>=2.0 +langchain-core>=0.3 +langchain-google-genai>=2.1 From da71e9814fda39f7368639e798c6f148f8dcbf33 Mon Sep 17 00:00:00 2001 From: Eylul Seyitoglu Date: Fri, 23 Oct 2026 15:40:55 +0300 Subject: [PATCH 04/10] test(backend): add API tests with a fake LLM --- backend/requirements-dev.txt | 3 ++ backend/tests/__init__.py | 0 backend/tests/conftest.py | 69 ++++++++++++++++++++++++ backend/tests/test_api.py | 101 +++++++++++++++++++++++++++++++++++ 4 files changed, 173 insertions(+) create mode 100644 backend/requirements-dev.txt create mode 100644 backend/tests/__init__.py create mode 100644 backend/tests/conftest.py create mode 100644 backend/tests/test_api.py diff --git a/backend/requirements-dev.txt b/backend/requirements-dev.txt new file mode 100644 index 0000000..2f21eed --- /dev/null +++ b/backend/requirements-dev.txt @@ -0,0 +1,3 @@ +-r requirements.txt +pytest>=8.0 +httpx>=0.27 diff --git a/backend/tests/__init__.py b/backend/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py new file mode 100644 index 0000000..080dbfa --- /dev/null +++ b/backend/tests/conftest.py @@ -0,0 +1,69 @@ +import os +import tempfile + +# Point the app at a throwaway database and make sure no real key is used +# before any app module is imported +_db_dir = tempfile.mkdtemp() +os.environ["DATABASE_URL"] = f"sqlite:///{_db_dir}/test.db" +os.environ["GOOGLE_API_KEY"] = "" + +import pytest +from fastapi.testclient import TestClient + +from main import app +from app.api.routes import get_recipe_service +from app.core.database import get_db +from app.models.recipe import GeneratedRecipe, ShoppingList +from app.services.recipe_service import RecipeService + + +class FakeStructuredLLM: + def __init__(self, response): + self.response = response + self.prompts = [] + + async def ainvoke(self, prompt): + self.prompts.append(prompt) + if isinstance(self.response, Exception): + raise self.response + return self.response + + +class FakeLLM: + """Stands in for ChatGoogleGenerativeAI, returning canned responses per schema.""" + + def __init__(self, responses): + self.structured = {schema: FakeStructuredLLM(r) for schema, r in responses.items()} + + def with_structured_output(self, schema): + return self.structured[schema] + + +SAMPLE_RECIPE = GeneratedRecipe( + title="Garlic Tomato Pasta", + ingredients=["200g pasta", "3 tomatoes", "2 cloves garlic", "fresh basil"], + instructions=["Boil pasta", "Make sauce", "Combine"], + cooking_time=20, + difficulty="Easy", + servings=2, + tags=["pasta", "vegetarian"], +) + + +@pytest.fixture +def fake_llm(): + return FakeLLM({ + GeneratedRecipe: SAMPLE_RECIPE, + ShoppingList: ShoppingList(shopping_list=["fresh basil"]), + }) + + +@pytest.fixture +def client(fake_llm): + def override(): + db = next(get_db()) + return RecipeService(db, llm=fake_llm) + + app.dependency_overrides[get_recipe_service] = override + yield TestClient(app) + app.dependency_overrides.clear() diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py new file mode 100644 index 0000000..2ff6c66 --- /dev/null +++ b/backend/tests/test_api.py @@ -0,0 +1,101 @@ +from app.models.recipe import GeneratedRecipe, ShoppingList +from app.services.recipe_service import RecipeService +from tests.conftest import FakeLLM, SAMPLE_RECIPE + + +def test_health(client): + assert client.get("/health").json()["status"] == "healthy" + + +def test_recommend_returns_recipe_without_shopping_list(client, fake_llm): + response = client.post("/api/v1/recipes/recommend", json={"ingredients": ["pasta", "Tomato", "garlic"]}) + + assert response.status_code == 200 + body = response.json() + assert body["title"] == "Garlic Tomato Pasta" + assert body["shopping_list"] == [] + # Shopping list is only generated when extra ingredients are allowed + assert fake_llm.structured[ShoppingList].prompts == [] + # Ingredients are normalised before reaching the prompt + assert "pasta, tomato, garlic" in fake_llm.structured[GeneratedRecipe].prompts[0] + + +def test_recommend_with_external_ingredients_builds_shopping_list(client): + response = client.post( + "/api/v1/recipes/recommend", + json={"ingredients": ["pasta", "tomato"], "allow_external_ingredients": True}, + ) + + assert response.status_code == 200 + assert response.json()["shopping_list"] == ["fresh basil"] + + +def test_prompt_includes_constraints(client, fake_llm): + client.post( + "/api/v1/recipes/recommend", + json={"ingredients": ["rice"], "dietary_preferences": ["vegan"], "max_cooking_time": 30}, + ) + + prompt = fake_llm.structured[GeneratedRecipe].prompts[0] + assert "suitable for vegan" in prompt + assert "must not exceed 30 minutes" in prompt + assert "\\n" not in prompt + + +def test_recommend_rejects_empty_ingredients(client): + assert client.post("/api/v1/recipes/recommend", json={"ingredients": []}).status_code == 422 + assert client.post("/api/v1/recipes/recommend", json={"ingredients": [" "]}).status_code == 422 + + +def test_llm_failure_returns_502(client, fake_llm): + fake_llm.structured[GeneratedRecipe].response = RuntimeError("boom") + + response = client.post("/api/v1/recipes/recommend", json={"ingredients": ["egg"]}) + + assert response.status_code == 502 + assert "boom" not in response.json()["detail"] + + +def test_llm_failure_does_not_count_ingredient_popularity(client, fake_llm): + fake_llm.structured[GeneratedRecipe].response = RuntimeError("boom") + + client.post("/api/v1/recipes/recommend", json={"ingredients": ["kohlrabi"]}) + + assert client.get("/api/v1/ingredients/suggestions", params={"query": "kohlrabi"}).json()["suggestions"] == [] + + +def test_shopping_list_failure_still_returns_recipe(client, fake_llm): + fake_llm.structured[ShoppingList].response = RuntimeError("boom") + + response = client.post( + "/api/v1/recipes/recommend", + json={"ingredients": ["pasta"], "allow_external_ingredients": True}, + ) + + assert response.status_code == 200 + assert response.json()["shopping_list"] == [] + + +def test_missing_api_key_returns_503(): + from fastapi.testclient import TestClient + from main import app + + response = TestClient(app).post("/api/v1/recipes/recommend", json={"ingredients": ["egg"]}) + + assert response.status_code == 503 + assert "GOOGLE_API_KEY" in response.json()["detail"] + + +def test_ingredient_suggestions_use_popularity(client): + client.post("/api/v1/recipes/recommend", json={"ingredients": ["zucchini"]}) + + response = client.get("/api/v1/ingredients/suggestions", params={"query": "zucc"}) + + assert response.json()["suggestions"] == ["zucchini"] + + +def test_suggestions_fall_back_to_common_ingredients(): + import asyncio + service = RecipeService(llm=FakeLLM({GeneratedRecipe: SAMPLE_RECIPE})) + + assert asyncio.run(service.get_ingredient_suggestions("garl")) == ["garlic"] From b5d2dcaca9cd0e3ca6570d4d01b5b2281e373edd Mon Sep 17 00:00:00 2001 From: Eylul Seyitoglu Date: Fri, 23 Oct 2026 15:45:13 +0300 Subject: [PATCH 05/10] fix(frontend): use ApiService and show backend error messages --- frontend/src/app/globals.css | 25 +---------- frontend/src/app/layout.tsx | 4 +- frontend/src/app/page.tsx | 29 +++++-------- frontend/src/components/FilterOptions.tsx | 6 ++- frontend/src/components/IngredientInput.tsx | 19 ++++++--- frontend/src/services/api.ts | 47 ++++++++++++--------- frontend/src/types/recipe.ts | 3 +- 7 files changed, 60 insertions(+), 73 deletions(-) diff --git a/frontend/src/app/globals.css b/frontend/src/app/globals.css index 18c2866..1b00d8c 100644 --- a/frontend/src/app/globals.css +++ b/frontend/src/app/globals.css @@ -1,32 +1,11 @@ @import "tailwindcss"; -:root { - --background: #ffffff; - --foreground: #171717; -} - @theme inline { - --color-background: var(--background); - --color-foreground: var(--foreground); --font-sans: var(--font-geist-sans); --font-mono: var(--font-geist-mono); } -@media (prefers-color-scheme: dark) { - :root { - --background: #0a0a0a; - --foreground: #ededed; - } -} - body { - background: var(--background); - color: var(--foreground); - font-family: Arial, Helvetica, sans-serif; -} - -@layer utilities { - .text-balance { - text-wrap: balance; - } + background: #fff7ed; + color: #171717; } diff --git a/frontend/src/app/layout.tsx b/frontend/src/app/layout.tsx index f7fa87e..2500ec5 100644 --- a/frontend/src/app/layout.tsx +++ b/frontend/src/app/layout.tsx @@ -13,8 +13,8 @@ const geistMono = Geist_Mono({ }); export const metadata: Metadata = { - title: "Create Next App", - description: "Generated by create next app", + title: "Cookable – AI Recipe Recommender", + description: "Turn the ingredients you already have into a recipe, powered by Google Gemini.", }; export default function RootLayout({ diff --git a/frontend/src/app/page.tsx b/frontend/src/app/page.tsx index c94cc9c..4911d15 100644 --- a/frontend/src/app/page.tsx +++ b/frontend/src/app/page.tsx @@ -5,6 +5,7 @@ import IngredientInput from '@/components/IngredientInput'; import RecipeDisplay from '@/components/RecipeDisplay'; import FilterOptions from '@/components/FilterOptions'; import { Recipe } from '@/types/recipe'; +import { ApiService } from '@/services/api'; export default function Home() { const [ingredients, setIngredients] = useState([]); @@ -27,24 +28,12 @@ export default function Home() { setError(null); try { - const response = await fetch('http://localhost:8000/api/v1/recipes/recommend', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - ingredients, - dietary_preferences: filters.dietary_preferences.length > 0 ? filters.dietary_preferences : undefined, - max_cooking_time: filters.max_cooking_time || undefined, - allow_external_ingredients: filters.allow_external_ingredients, - }), + const recipeData = await ApiService.getRecipeRecommendation({ + ingredients, + dietary_preferences: filters.dietary_preferences.length > 0 ? filters.dietary_preferences : undefined, + max_cooking_time: filters.max_cooking_time ?? undefined, + allow_external_ingredients: filters.allow_external_ingredients, }); - - if (!response.ok) { - throw new Error('Failed to get recipe recommendation'); - } - - const recipeData = await response.json(); setRecipe(recipeData); } catch (err) { setError(err instanceof Error ? err.message : 'An error occurred'); @@ -70,7 +59,7 @@ export default function Home() { {/* Header */}

- 🍳 Recipe Recommender + 🍳 Cookable

Enter your available ingredients and get AI-powered recipe suggestions @@ -104,6 +93,7 @@ export default function Home() { {/* Step 3: Get Recipe Button */}

- If enabled, we'll suggest recipes that might require a few extra items, and we'll provide a shopping list for them. + If enabled, we'll suggest recipes that might require a few extra items, and we'll provide a shopping list for them.

@@ -91,6 +91,7 @@ export default function FilterOptions({ filters, onFiltersChange }: FilterOption

Maximum Cooking Time:

{cookingTimeOptions.map((option) => (