search
HomeBackend DevelopmentPython TutorialBuilding a GenAI Fitness App with Gemini

Last summer, when I found out about the Gemini API Developer Competition, I saw it as a great chance to get my hands dirty with GenAI applications. As fitness enthusiasts, we (me & Manos Chainakis) thought of creating an app that could generate personalised workout and nutrition plans—combining AI with the preferences of human coaches. That’s how Fitness Tribe AI was born. This post will walk you through the development process and the tech stack I used, with focus on the GenAI aspect.

Building a GenAI Fitness App with Gemini

Fitness Tribe AI  |  Gemini API Developer Competition  |  Google AI for Developers

Making Personal Training Better for Everyone, Everywhere.

Building a GenAI Fitness App with Gemini ai.google.dev

The Concept Behind Fitness Tribe AI

Fitness Tribe AI combines the expertise of human coaches with the capabilities of AI models to create custom fitness programs that meet each athlete's needs and goals.

The Tech Stack

The main components of the tech stack are:

  • FastAPI for the backend and AI model integration
  • Supabase for user authentication and data management
  • Ionic & Angular for the frontend mobile app
  • Astro for the landing page

FastAPI: Backend and AI Integration

FastAPI serves as the backbone of Fitness Tribe AI, handling the AI-powered analysis.

Here’s how the project is structured:

fitness-tribe-ai/
├── app/
│   ├── main.py              # Entry point for FastAPI app
│   ├── routers/             # Handles API routes (meals, nutrition, workouts)
│   ├── models/              # Manages interactions with AI models
│   ├── schemas/             # Pydantic models for input validation
│   ├── services/            # Business logic for each feature

Key elements of the FastAPI implementation:

  • API Routing: Routes are divided into separate files for meals (meals.py), workouts (workouts.py), and nutrition (nutrition.py), keeping the API structure organised and scalable. Each router is connected in main.py, where FastAPI’s routing system ties everything together.
from fastapi import FastAPI
from app.routers import meals, nutrition, workouts

app = FastAPI()

app.include_router(meals.router)
app.include_router(nutrition.router)
app.include_router(workouts.router)
  • Gemini Model Integration: The GeminiModel class, in gemini_model.py, handles the AI model interaction. Taking as an example the meal analyzer method, I am using Pillow to process image data, and the app sends both the image and a custom prompt to the Gemini AI to analyze meal details. An important detail here is that the prompt should be specific enough, when it comes to the format of the expected response, so that it can be processed by the service layer.
class GeminiModel:
    @staticmethod
    def analyze_meal(image_data):
        prompt = (
            "Analyze the following meal image and provide the name of the food, "
            "total calorie count, and calories per ingredient..."
            "Respond in the following JSON format:"
            "{'food_name': '<food name>' ...}"
        )
        image = Image.open(BytesIO(image_data))
        response = model.generate_content([prompt, image])
        return response.text
</food>
  • Pydantic Schema for Data Validation: The response from the AI model is validated and structured using Pydantic models. For instance, the Meal schema in schemas/meal.py ensures the response is consistent before it is returned to the user.
from pydantic import BaseModel
from typing import Dict

class Meal(BaseModel):
    food_name: str
    total_calories: int
    calories_per_ingredient: Dict[str, int]
  • Service Layer: The service layer, located in services/, encapsulates the logic of each feature. For example, the meal_service.py handles the meal analysis, ensuring the data is properly processed before returning the AI results.
from app.models.gemini_model import GeminiModel
from app.schemas.meal import Meal
from fastapi import HTTPException
import logging
import json

def analyze_meal(image_data: bytes) -> Meal:
    try:
        result_text = GeminiModel.analyze_meal(image_data)
        if not result_text:
            raise HTTPException(status_code=500, detail="No response from Gemini API")

        clean_result_text = result_text.strip("```

json\n").strip("

```")
        result = json.loads(clean_result_text)
        return Meal(
            food_name=result.get("food_name"),
            total_calories=result.get("total_calories"),
            calories_per_ingredient=result.get("calories_per_ingredient"),
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

By leveraging FastAPI’s modular structure, clear API routing, Pydantic for data validation, and well-organized service logic, Fitness Tribe AI efficiently handles AI model interactions with custom prompts to deliver personalized fitness and nutrition insights. You can find the full repo here:

Building a GenAI Fitness App with Gemini fitness-tribe / fitness-tribe-ai

Fitness Tribe AI is an AI-powered API, providing endpoints for coaches and athletes.

Fitness Tribe API

Fitness Tribe AI is an AI-powered fitness API designed for coaches and athletes. The API provides meal analysis functionality by analyzing meal photos and an AI powered workout builder, which can generate workout plans based on athlete profiles. Fitness Tribe AI has been built the Gemini model.

Features

  • Meal Analysis: Upload a photo of a meal to receive a detailed analysis of its ingredients and calorie count.
  • Workout Builder: Input an athlete's profile details to receive a personalized workout plan tailored to the athlete's fitness goal.

Project Structure

fitness-tribe-ai/
├── app/
│   ├── __init__.py
│   ├── main.py
│   ├── models/
│   │   ├── __init__.py
│   │   ├── gemini_model.py
│   ├── routers/
│   │   ├── __init__.py
│   │   ├── meals.py
│   │   ├── nutrition.py
│   │   ├── workouts.py
│   ├── schemas/
│   │   ├── __init__.py
│   │   ├── meal.py
│   │   ├── nutrition.py
│   │   ├──
View on GitHub

Supabase: User Management & Auth

For user authentication and account management, I used Supabase, which provided a secure, scalable solution without requiring a custom-built authentication system.

Key features I leveraged:

  • Authentication: Supabase's built-in authentication enabled users to log in and manage their profiles with ease.

  • Database Management: Using Supabase’s PostgreSQL-backed database, I stored user preferences, workout routines, and meal plans to ensure updates reflected immediately in the app.

Ionic & Angular: Cross-Platform Frontend

For the frontend, I chose Ionic and Angular, which enabled me to create a mobile-first app that could be deployed on the web right away while it could also be shipped as native for both iOS and Android.

Astro: A Lightning-Fast Landing Page

For the landing page, I opted for Astro, which focuses on performance by shipping minimal JavaScript. Astro allowed me to build a fast, lightweight page that efficiently showcased the app.

Conclusion

Developing Fitness Tribe AI was a learning journey that enabled me to explore the power that AI models give us nowadays. Each framework played a role, from FastAPI’s robust backend capabilities and ease of use to Supabase’s user management, Ionic’s cross-platform frontend and Astro’s high-performance landing pages.

For anyone looking to build a GenAI app, I highly recommend exploring these frameworks (and especially FastAPI) for their powerful features and smooth developer experience.

Have questions or want to learn more about it? Let me know in the comments!

The above is the detailed content of Building a GenAI Fitness App with Gemini. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to Use Python to Find the Zipf Distribution of a Text FileHow to Use Python to Find the Zipf Distribution of a Text FileMar 05, 2025 am 09:58 AM

This tutorial demonstrates how to use Python to process the statistical concept of Zipf's law and demonstrates the efficiency of Python's reading and sorting large text files when processing the law. You may be wondering what the term Zipf distribution means. To understand this term, we first need to define Zipf's law. Don't worry, I'll try to simplify the instructions. Zipf's Law Zipf's law simply means: in a large natural language corpus, the most frequently occurring words appear about twice as frequently as the second frequent words, three times as the third frequent words, four times as the fourth frequent words, and so on. Let's look at an example. If you look at the Brown corpus in American English, you will notice that the most frequent word is "th

Image Filtering in PythonImage Filtering in PythonMar 03, 2025 am 09:44 AM

Dealing with noisy images is a common problem, especially with mobile phone or low-resolution camera photos. This tutorial explores image filtering techniques in Python using OpenCV to tackle this issue. Image Filtering: A Powerful Tool Image filter

How Do I Use Beautiful Soup to Parse HTML?How Do I Use Beautiful Soup to Parse HTML?Mar 10, 2025 pm 06:54 PM

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

How to Perform Deep Learning with TensorFlow or PyTorch?How to Perform Deep Learning with TensorFlow or PyTorch?Mar 10, 2025 pm 06:52 PM

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

Introduction to Parallel and Concurrent Programming in PythonIntroduction to Parallel and Concurrent Programming in PythonMar 03, 2025 am 10:32 AM

Python, a favorite for data science and processing, offers a rich ecosystem for high-performance computing. However, parallel programming in Python presents unique challenges. This tutorial explores these challenges, focusing on the Global Interprete

How to Implement Your Own Data Structure in PythonHow to Implement Your Own Data Structure in PythonMar 03, 2025 am 09:28 AM

This tutorial demonstrates creating a custom pipeline data structure in Python 3, leveraging classes and operator overloading for enhanced functionality. The pipeline's flexibility lies in its ability to apply a series of functions to a data set, ge

Serialization and Deserialization of Python Objects: Part 1Serialization and Deserialization of Python Objects: Part 1Mar 08, 2025 am 09:39 AM

Serialization and deserialization of Python objects are key aspects of any non-trivial program. If you save something to a Python file, you do object serialization and deserialization if you read the configuration file, or if you respond to an HTTP request. In a sense, serialization and deserialization are the most boring things in the world. Who cares about all these formats and protocols? You want to persist or stream some Python objects and retrieve them in full at a later time. This is a great way to see the world on a conceptual level. However, on a practical level, the serialization scheme, format or protocol you choose may determine the speed, security, freedom of maintenance status, and other aspects of the program

Mathematical Modules in Python: StatisticsMathematical Modules in Python: StatisticsMar 09, 2025 am 11:40 AM

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively. This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the mean() function instead of simply summing the average. Floating point numbers can also be used. import random import statistics from fracti

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),