Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 20 additions & 6 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,29 @@ jobs:
defaults:
run:
working-directory: backend
services:
# Same image as compose.yaml; tests create their own cookable_test database
postgres:
image: pgvector/pgvector:0.8.7-pg18
env:
POSTGRES_USER: cookable
POSTGRES_PASSWORD: cookable
POSTGRES_DB: cookable
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -U cookable"
--health-interval 5s
--health-timeout 3s
--health-retries 10
steps:
- uses: actions/checkout@v5
- uses: actions/setup-python@v6
- uses: astral-sh/setup-uv@v10.3.2
with:
python-version: "3.12"
cache: pip
cache-dependency-path: backend/requirements*.txt
- run: pip install -r requirements-dev.txt
- run: pytest -q
python-version: "3.14"
enable-cache: true
- run: uv sync --locked
- run: uv run pytest -q

frontend:
name: Frontend (lint, typecheck, build)
Expand Down
148 changes: 8 additions & 140 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,154 +3,22 @@
[![CI](https://github.com/eylulseyit/Cookable/actions/workflows/ci.yml/badge.svg?branch=dev)](https://github.com/eylulseyit/Cookable/actions/workflows/ci.yml)
[![License: AGPL-3.0](https://img.shields.io/badge/license-AGPL--3.0-blue.svg)](LICENSE)

Cookable turns the ingredients you already have into a recipe. Enter what's in your kitchen, pick optional filters, and Google Gemini generates a complete recipe, plus a shopping list if you allow a few extra ingredients.
Cookable helps you cook with what you already have. Tell it what's in your kitchen and it suggests a recipe, along with a shopping list for anything missing.

## Features
The goal is a meal planner that knows your pantry: snap a photo of your fridge, keep track of your ingredients, and get a weekly plan that fits your diet and nutrition goals.

- **Ingredient-based recipes**: add ingredients one by one or from quick-add suggestions
- **Filters**: dietary preferences (vegetarian, vegan, gluten-free, ...) and a maximum cooking time
- **Shopping list**: when extra ingredients are allowed, a second step compares the recipe with what you have and lists what to buy
- **Reliable AI output**: recipes are generated with LangChain structured output, so Gemini's response is validated against a Pydantic schema instead of parsed by hand
- **Graceful failure handling**: clear 422 / 502 / 503 errors, and the recipe is still returned if only the shopping list step fails
> **Work in progress.** Cookable is in active development, so things change often.

## Tech Stack
## Running locally

| Layer | Technologies |
|---|---|
| Frontend | React 19, TypeScript, Vite, Tailwind CSS 4 |
| Backend | Python 3.12, FastAPI, Pydantic, SQLAlchemy, SQLite |
| AI | Google Gemini (`gemini-2.5-flash`) via LangChain |
| Testing | pytest with a fake LLM (no API key or network needed) |
| Tooling | pnpm, Docker / Podman, Docker Compose, GitHub Actions |

## Architecture

```mermaid
flowchart LR
U[Browser] -->|static files| F[Frontend<br/>React SPA built with Vite<br/>served by nginx]
U -->|REST /api/v1| B[Backend<br/>FastAPI]
B -->|structured output| G[Google Gemini]
B --> D[(SQLite)]
```

The frontend is a fully client-side React app that Vite builds to static files, so it can be served by any static host. All AI work happens in the FastAPI backend, which keeps the API key on the server.

## Quick Start (Docker / Podman)

**Prerequisites:** Docker or Podman with Compose, and a free [Gemini API key](https://aistudio.google.com/apikey).

```bash
git clone https://github.com/eylulseyit/Cookable.git
cd Cookable

cp backend/.env.example backend/.env
# Open backend/.env and set GOOGLE_API_KEY

docker compose up --build # or: podman compose up --build
```

- App: http://localhost:3000
- API docs (Swagger UI): http://localhost:8000/docs

Stop with `Ctrl+C`, then `docker compose down`. Recipe data is kept in a named volume between runs.

## Local Development

Run the backend and frontend in two terminals for hot reload.

**Backend** (Python 3.12+):
You need Docker or Podman with Compose, and a free [Gemini API key](https://aistudio.google.com/apikey).

```bash
cd backend
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install -r requirements-dev.txt
cp .env.example .env # then set GOOGLE_API_KEY
uvicorn main:app --reload
cp backend/.env.example backend/.env # then set GOOGLE_API_KEY
docker compose up --build # or: podman compose up --build
```

Optionally seed the database with sample ingredients and tags: `python init_db.py`.

**Frontend** (Node.js 22+, pnpm):

```bash
cd frontend
pnpm install
pnpm dev
```

The frontend calls `http://localhost:8000/api/v1` by default. Set `VITE_API_URL` (see `frontend/.env.example`) to point it elsewhere.

## Configuration

Backend settings are read from environment variables or `backend/.env`:

| Variable | Default | Description |
|---|---|---|
| `GOOGLE_API_KEY` | (required) | Gemini API key |
| `GEMINI_MODEL` | `gemini-2.5-flash` | Gemini model used for generation |
| `DATABASE_URL` | `sqlite:///backend/cookable.db` | SQLAlchemy database URL |
| `CORS_ORIGINS` | `http://localhost:3000,http://127.0.0.1:3000` | Comma-separated allowed origins |

> The Gemini free tier is rate-limited (a few requests per minute for `gemini-2.5-flash`). If you hit the limit, the API returns an error and you can retry after a minute.

## API

| Method | Endpoint | Description |
|---|---|---|
| `POST` | `/api/v1/recipes/recommend` | Generate a recipe from ingredients and filters |
| `GET` | `/api/v1/ingredients/suggestions?query=` | Ingredient suggestions based on past usage |
| `GET` | `/api/v1/ingredients/popular` | Most frequently used ingredients |
| `GET` | `/health` | Health check |

Example request:

```bash
curl -X POST http://localhost:8000/api/v1/recipes/recommend \
-H "Content-Type: application/json" \
-d '{"ingredients": ["egg", "tomato", "onion"], "allow_external_ingredients": true}'
```

Full, interactive documentation is available at `/docs` while the backend is running.

## Testing and CI

```bash
cd backend
pytest
```

The tests replace Gemini with a fake model through FastAPI dependency overrides, so they run offline in well under a second and need no API key.

GitHub Actions runs on every push to `dev` and `main` and on pull requests:

- **Backend**: pytest
- **Frontend**: ESLint, TypeScript type check, production build
- **Containers**: builds both images with Docker Compose

## Project Structure

```
Cookable/
├── backend/
│ ├── app/
│ │ ├── api/ # FastAPI routes
│ │ ├── core/ # Settings and database setup
│ │ ├── models/ # Pydantic schemas and SQLAlchemy models
│ │ └── services/ # Recipe generation and database logic
│ ├── tests/ # pytest suite with a fake LLM
│ ├── main.py # FastAPI application entry point
│ └── Dockerfile
├── frontend/
│ ├── src/
│ │ ├── App.tsx # Root component
│ │ ├── components/ # React components
│ │ ├── services/ # API client
│ │ └── types/ # TypeScript types
│ └── Dockerfile
├── compose.yaml
└── .github/workflows/ # CI pipeline
```
Open http://localhost:3000.

## License

Expand Down
2 changes: 1 addition & 1 deletion backend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@ GOOGLE_API_KEY=

# Optional overrides
# GEMINI_MODEL=gemini-2.5-flash
# DATABASE_URL=sqlite:///./cookable.db
# DATABASE_URL=postgresql+psycopg://cookable:cookable@localhost:5432/cookable
# CORS_ORIGINS=http://localhost:3000,http://127.0.0.1:3000
29 changes: 15 additions & 14 deletions backend/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,28 +1,29 @@
FROM docker.io/library/python:3.12-slim
FROM docker.io/library/python:3.14-slim

COPY --from=ghcr.io/astral-sh/uv:0.12.3 /uv /bin/uv

ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PIP_NO_CACHE_DIR=1 \
PIP_DISABLE_PIP_VERSION_CHECK=1
UV_COMPILE_BYTECODE=1 \
UV_LINK_MODE=copy \
UV_NO_CACHE=1 \
PATH="/app/.venv/bin:$PATH"

WORKDIR /app

# Install dependencies first so this layer is cached when only code changes
COPY requirements.txt .
RUN pip install -r requirements.txt
# Install dependencies first so this layer is cached when only code changes;
# --locked fails the build if uv.lock is out of date with pyproject.toml
COPY pyproject.toml uv.lock ./
RUN uv sync --locked --no-dev

COPY app ./app
COPY main.py init_db.py ./
COPY migrations ./migrations
COPY main.py alembic.ini ./

# Run as an unprivileged user; /data holds the SQLite database
RUN useradd --create-home --uid 10001 cookable \
&& mkdir /data && chown cookable /data
# Run as an unprivileged user
RUN useradd --create-home --uid 10001 cookable
USER cookable

ENV DATABASE_URL=sqlite:////data/cookable.db
EXPOSE 8000

HEALTHCHECK --interval=30s --timeout=3s --start-period=10s \
CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health')"

CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
149 changes: 149 additions & 0 deletions backend/alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
# A generic, single database configuration.

[alembic]
# path to migration scripts.
# this is typically a path given in POSIX (e.g. forward slashes)
# format, relative to the token %(here)s which refers to the location of this
# ini file
script_location = %(here)s/migrations

# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
# Or organize into date-based subdirectories (requires recursive_version_locations = true)
# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s

# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory. for multiple paths, the path separator
# is defined by "path_separator" below.
prepend_sys_path = .


# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the tzdata library which can be installed by adding
# `alembic[tz]` to the pip requirements.
# string value is passed to ZoneInfo()
# leave blank for localtime
# timezone =

# max length of characters to apply to the "slug" field
# truncate_slug_length = 40

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false

# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false

# version location specification; This defaults
# to <script_location>/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "path_separator"
# below.
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions

# path_separator; This indicates what character is used to split lists of file
# paths, including version_locations and prepend_sys_path within configparser
# files such as alembic.ini.
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
# to provide os-dependent path splitting.
#
# Note that in order to support legacy alembic.ini files, this default does NOT
# take place if path_separator is not present in alembic.ini. If this
# option is omitted entirely, fallback logic is as follows:
#
# 1. Parsing of the version_locations option falls back to using the legacy
# "version_path_separator" key, which if absent then falls back to the legacy
# behavior of splitting on spaces and/or commas.
# 2. Parsing of the prepend_sys_path option falls back to the legacy
# behavior of splitting on spaces, commas, or colons.
#
# Valid values for path_separator are:
#
# path_separator = :
# path_separator = ;
# path_separator = space
# path_separator = newline
#
# Use os.pathsep. Default configuration used for new projects.
path_separator = os

# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false

# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8

# database URL. This is consumed by the user-maintained env.py script only.
# other means of configuring database URLs may be customized within the env.py
# file.
# sqlalchemy.url is set from DATABASE_URL in migrations/env.py


[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples

# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME

# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
# hooks = ruff
# ruff.type = module
# ruff.module = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME

# Alternatively, use the exec runner to execute a binary found on your PATH
# hooks = ruff
# ruff.type = exec
# ruff.executable = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME

# Logging configuration. This is also consumed by the user-maintained
# env.py script only.
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARNING
handlers = console
qualname =

[logger_sqlalchemy]
level = WARNING
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
Loading
Loading