Consider an app wherein you click the picture of your meal and results pop up all the nutritional details about the food items in that meal. The “Healthify Your Diet Tracker” app aims to track your diet plan by recognizing the food from the picture and using data that can be useful in a diet plan. Be it losing weight, building muscles, or maintaining a healthy life; such a tool will prove to be highly effective in achieving all these goals.
Welcome to the “Healthify Your Diet Tracker” project. It’s your go-to tutorial where developers will learn to make the most out of generative AI models within vision models. This tutorial is perfect for any proficient programmer looking to add an extra trick up their sleeve or any curious beginner who would like to see AI in action.
This project shows you how to leverage generative AI in building your diet-tracking application. It enables you to take a picture of what you eat, and it will automatically detect the food, which is broken down further to give you information on its nutritional content so that users can easily keep track of their diet, weight loss, or gain goals embarking on a healthy lifestyle
What You’ll Learn
Generative AI and Vision Models: This book makes one learn generative AI and the working of vision models. One learns the image recognition and classification principles in detail.
Apply Pre-trained Models: You will learn how to use a pre-trained model and save direct labor that results in the consumption of a lot of time and resources. You are shown how to integrate these models in your application in the most effective manner.
Full Stack Application: You will gain hands-on experience in full-stack development by setting up a development environment, creating or designing a user-friendly user interface, and lastly, building a backend robustly.
Industrial-level project development: This course offers insight into developing AI projects at an industrial scale. The course talks about the considerations of projects taken on an industrial level. Such considerations include Scalability, performance, security, etc.
Deployment: Learn how to deploy your application on a server so people worldwide can access it including an overview of different platforms to deploy your app and maintain the deployed application.
Why This Project?
Real-World Uses: There are quite several applications to which you can readily apply AI to substantially change people’s lives. Food recognition, for example, as well as nutritional analysis.
Hands-On Experience: From this project, you will gain experience that could be applied directly to future projects or even working professionally.
Broad Range of Practice The project covers UI/UX design, backend development, building the AI, and deployment-which essentially means you get to cover an extensive variety of areas in one learning experience.
Setup Python and VS code
Got it! Here’s the revised setup guide for installing Python and VS Code on Windows:
Installing Python on Windows
- Download Python:
- Go to the official Python website.
- Click on the “Downloads” tab.
- Click “Download Python 3.x.x” (the latest version).
- Install Python:
- Open the downloaded installer.
- Important: Check the box that says “Add Python to PATH” at the bottom of the installer window.
- Click “Install Now” and follow the prompts.
- Verify Python Installation:
- Open Command Prompt (search for “cmd” in the Start menu).
- Type
python --version
and press Enter. You should see the version of Python you installed. - Type
pip --version
and press Enter. You should see the version of pip, which is Python’s package installer.
Installing Visual Studio Code (VS Code) on Windows
- Download VS Code:
- Go to the VS Code website.
- Click “Download for Windows”.
- Install VS Code:
- Open the downloaded installer.
- Follow the installation prompts.
- You can select additional tasks like creating a desktop icon and adding VS Code to PATH.
Installing Python on macOS
- Check Pre-installed Python:
- Open Terminal (you can find it in Applications > Utilities or search for it using Spotlight).
- Type
python3 --version
and press Enter. macOS usually comes with Python 2.x and Python 3.x pre-installed. Check if you need to install a newer version.
- Download Python:
- Go to the official Python website.
- Click on the “Downloads” tab.
- Click “Download Python 3.x.x” (the latest version).
- Install Python:
- Open the downloaded
.pkg
file. - Follow the installation prompts.
- Open the downloaded
- Verify Python Installation:
- Open Terminal.
- Type
python3 --version
and press Enter. You should see the version of Python you installed. - Type
pip3 --version
and press Enter. You should see the version of pip, which is Python’s package installer.
Installing Visual Studio Code (VS Code) on macOS
- Download VS Code:
- Go to the VS Code website.
- Click “Download for macOS”.
- Install VS Code:
- Open the downloaded
.zip
file. This will extract the application. - Drag the Visual Studio Code application to your Applications folder.
- Open the downloaded
- Add VS Code to PATH:
- Open VS Code.
- Press
Cmd+Shift+P
to open the Command Palette. - Type
Shell Command: Install 'code' command in PATH
and select the option.
Installing Python on Linux
Step 1: Check if Python is Already Installed
- Open a terminal.
- Type python3 –version and press Enter. Most Linux distributions come with Python pre-installed. This command will check if Python 3 is installed and show its version.
Step 2: Update Package List
- Open a terminal.
- Type sudo apt update and press Enter to update the package list.
Step 3: Install Python
For Debian-based systems (like Ubuntu):
- Type sudo apt install python3 and press Enter.
Step 4: Verify Python Installation
- Open a terminal.
- Type python3 –version and press Enter. You should see the version of Python you installed.
- Type pip3 –version and press Enter. You should see the version of pip, which is Python’s package installer.
Installing Visual Studio Code (VS Code) on Linux
Step 1: Download and Install VS Code
- Open a terminal.
- For Debian-based systems (like Ubuntu):
Add the repository and install via these commands:sudo apt update
sudo apt install software-properties-common apt-transport-https wget
wget -q https://packages.microsoft.com/keys/microsoft.asc -O- | sudo apt-key add -
sudo add-apt-repository "deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main"
sudo apt update
sudo apt install code
Step 2: Verify VS Code Installation
- Open a terminal.
- Type code –version and press Enter. You should see the version of VS Code you installed.
Adding VS Code to PATH (Optional)
- Open VS Code.
- Press Ctrl+Shift+P to open the Command Palette.
- Type `Shell Command: Install the ‘code’ command in PATH` and select the option.
Setting Up a Virtual Environment for the ‘Healthify’ Project and Installing Required Libraries
A virtual environment is a self-contained directory that contains a Python installation and a set of libraries. It allows you to manage dependencies for your project separately from the system-wide Python installation, ensuring that your project has access to the specific libraries and versions it needs without conflicts.
Step-by-Step Guide
1. Open Command Prompt
- Press
Win + R
, typecmd
, and press Enter.
2. Navigate to Your Project Directory
- Use the
cd
command to navigate to your project directory. - For example:
- cd C:\path\to\your\projects
3. Create a Directory for Your Project
- Create a directory for your project named
healthify
and navigate into it: mkdir healthify cd healthify
4. Create a Virtual Environment
- Run the following command to create a virtual environment named
healthify
: python -m venv healthify
5. Activate the Virtual Environment
- Activate the virtual environment using the following command:
.\healthify\Scripts\activate
- You should see
(healthify)
at the beginning of the command prompt line, indicating that the virtual environment is active.
6. Install Required Libraries
- With the virtual environment active, install the required libraries using
pip install flask gradio transformers pillow python-dotenv
Setting Up the Project Folder and Files for ‘Healthify’
Creating the Project Folder in VS Code
Option 1: Automated Setup Using a Script
Let’s create a script that will automatically set up the folder structure and necessary files for your project.
- Open VS Code
- Open Visual Studio Code.
- Open Terminal in VS Code
- Open the terminal by going to View > Terminal or using the shortcut Ctrl+`.
- Open your project folder: open your project folder
- Create a Python Script for Setup
- Create a file named set_up.py.
- Add Setup Code to the Script
Copy and paste the following code into set_up.py:
import os
# Define the structure of the project
folders = [
'static/assets/images',
'static/assets/icons',
'templates',
'src',
'docs/notebook'
]
files = {
'static/styles.css': '',
'templates/index.html': '',
'src/main.py': '',
'src/classifier.py': '',
'src/nutrition_info.py': '',
'app.py': '',
'.env': '',
'docs/notebook/notes.txt': ''
}
# Create directories
for folder in folders:
os.makedirs(folder, exist_ok=True)
# Create files
for file_path, content in files.items():
with open(file_path, 'w') as file:
file.write(content)
print("Project structure created successfully.")
- Run the Setup Script
In the terminal, run the script to create the folder structure and files:
python set_up.py
You should see a message: Project structure created successfully.
Option 2: Manual Setup
If you prefer to create the folders and files manually, follow these steps:
- Create Folders and Files Manually
- Open VS Code and navigate to your project directory.
- Create the following folders:
- static
- static/assets
- static/assets/images
- static/assets/icons
- templates
- src
- docs
- docs/notebook
- Create the following files in their respective directories:
- static/styles.css
- templates/index.html
- src/main.py
- src/classifier.py
- src/nutrition_info.py
- app.py
- .env
- docs/notebook/notes.txt
- Verify the Structure
Ensure your project structure looks like this:
healthify/
├── static/
│ ├── assets/
│ │ ├── images/
│ │ └── icons/
│ └── styles.css
├── templates/
│ └── index.html
├── src/
│ ├── main.py
│ ├── classifier.py
│ └── nutrition_info.py
├── docs/
│ └── notebook/
│ └── notes.txt
├── app.py
- └── .env
Building Home Page Using Flask Server
2. Copy the HTML Template and Static Files:
- If you have an
index.html
file and static files (likestyles.css
, images) for your website, copy them into the appropriate folders (templates
andstatic
).
3. Set Up Flask Server:
past in app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
Run Flask Server:
- Open your terminal.
- Navigate to your project directory.
- Run the Flask server by executing
python app.py
. - Your Flask server should start, and you can access it at
http://127.0.0.1:5000
in your web browser.
Building Gradio Interface
Gradio is a Python library that simplifies the creation of user interfaces for machine learning models and data science applications. It allows you to build interactive web applications with minimal code, making it easy to share and test models or functions with others. With Gradio, you can create interfaces for uploading images, text, audio, and more, and then process these inputs with your Python functions.
Code Explanation
Let’s break down the provided code step by step.
1. Importing Libraries
from PIL import Image
import gradio as gr
- PIL: The Python Imaging Library, used here for handling image files.
- gradio: The Gradio library for building the user interface.
2. Defining the display_dummy_data Function
def display_dummy_data(image):
“””Return dummy nutritional information as an HTML table.”””
This function takes an image as input and returns a string containing HTML code for a table with dummy nutritional information.
3. Dummy Nutritional Data
dummy_data = {
‘name’: ‘Dummy Food’,
‘calories’: 100,
‘serving_size_g’: 100,
‘fat_total_g’: 5,
‘fat_saturated_g’: 1,
‘protein_g’: 2,
‘sodium_mg’: 50,
‘potassium_mg’: 200,
‘cholesterol_mg’: 0,
‘carbohydrates_total_g’: 20,
‘fiber_g’: 3,
‘sugar_g’: 10
}
This dictionary contains sample nutritional data for a fictional food item.
4. Creating the HTML Table
The table variable is a string that contains HTML code for a table displaying the dummy data.
table = f”””
<table border=”1″ style=”width: 100%; border-collapse: collapse; font-family: Arial, sans-serif; margin-top: 20px;”>
<tr style=”background-color: #f2f2f2;”><th colspan=”4″ style=”text-align: center; padding: 10px;”><b>Nutrition Facts</b></th></tr>
<tr><td colspan=”4″ style=”text-align: center; padding: 10px;”><b>Food Name: {dummy_data[‘name’]}</b></td></tr>
<tr style=”background-color: #e6f7ff;”>
<td style=”padding: 8px;”><b>Calories</b></td><td style=”padding: 8px; text-align: right;”>{dummy_data[‘calories’]}</td>
<td style=”padding: 8px;”><b>Serving Size (g)</b></td><td style=”padding: 8px; text-align: right;”>{dummy_data[‘serving_size_g’]}</td>
</tr>
<tr>
<td style=”padding: 8px;”><b>Total Fat (g)</b></td><td style=”padding: 8px; text-align: right;”>{dummy_data[‘fat_total_g’]}</td>
<td style=”padding: 8px;”><b>Saturated Fat (g)</b></td><td style=”padding: 8px; text-align: right;”>{dummy_data[‘fat_saturated_g’]}</td>
</tr>
<tr style=”background-color: #e6f7ff;”>
<td style=”padding: 8px;”><b>Protein (g)</b></td><td style=”padding: 8px; text-align: right;”>{dummy_data[‘protein_g’]}</td>
<td style=”padding: 8px;”><b>Sodium (mg)</b></td><td style=”padding: 8px; text-align: right;”>{dummy_data[‘sodium_mg’]}</td>
</tr>
<tr>
<td style=”padding: 8px;”><b>Potassium (mg)</b></td><td style=”padding: 8px; text-align: right;”>{dummy_data[‘potassium_mg’]}</td>
<td style=”padding: 8px;”><b>Cholesterol (mg)</b></td><td style=”padding: 8px; text-align: right;”>{dummy_data[‘cholesterol_mg’]}</td>
</tr>
<tr style=”background-color: #e6f7ff;”>
<td style=”padding: 8px;”><b>Total Carbohydrates (g)</b></td><td style=”padding: 8px; text-align: right;”>{dummy_data[‘carbohydrates_total_g’]}</td>
<td style=”padding: 8px;”><b>Fiber (g)</b></td><td style=”padding: 8px; text-align: right;”>{dummy_data[‘fiber_g’]}</td>
</tr>
<tr>
<td style=”padding: 8px;”><b>Sugar (g)</b></td><td style=”padding: 8px; text-align: right;”>{dummy_data[‘sugar_g’]}</td>
<td></td><td></td>
</tr>
</table>
“””
This HTML table is formatted to look like a nutrition label, displaying all the dummy nutritional information.
5. Creating the Gradio Interface
iface = gr.Interface(
fn=display_dummy_data,
inputs=gr.Image(type=”filepath”),
outputs=”html”,
title=”Food Identification and Nutrition Info”,
description=”Upload an image of food to get dummy nutritional information.”,
allow_flagging=”never”
)
- fn=display_dummy_data: Specifies the function to be called when an image is uploaded.
- inputs=gr.Image(type=”filepath”): Sets the input type to an image file.
- outputs=”html”: The function’s output will be rendered as HTML.
- title and description: Provide a title and description for the interface.
- allow_flagging=”never”: Disables the flagging option in the Gradio interface.
6. Launch the Gradio Interface
iface.launch()
7. To run the code, follow these steps in your terminal:
cd src
python run main.py
Download Load and Feature Extract in Notebook
Pre-trained Model: It is a model from machine learning trained beforehand on a large dataset. It is then fine-tuned for specific tasks. It will save time and resources since one does not have to train the model right from the beginning.
Transformer: They are a class of deep learning-based models that have transformed most NLP and image data tasks. This is because they can relate and connect the different parts of input data although in a very simple manner, thus adding to the understanding and, hence, prediction.
Why Use “google/vit-base-patch16-224”?
“google/vit-base-patch16-224” is a Vision Transformer, ViT.
SOTA on image classification tasks.
Thus, it uses a large dataset, enabling it to detect virtually any object occupying the image.
It is used to automate the extraction of features from image
Receiving API for Nutrition Information
In receiving nutrition information, API-ninjas.com sends a request based on a prediction from the food label.
from PIL import Image
from dotenv import load_dotenv
import os
import requests
from transformers import ViTFeatureExtractor, ViTForImageClassification
import warnings
warnings.filterwarnings(“ignore”) # Ignore warnings for cleaner output
Load environment variables
load_dotenv()
model_name = os.getenv(“MODEL”) # Get model name from environment variables
secret_key = os.getenv(‘API_KEY’) # Get API key from environment variables
Load the pre-trained vision Transformer model and feature extractor
feature_extractor = ViTFeatureExtractor.from_pretrained(model_name)
model = ViTForImageClassification.from_pretrained(model_name)
Load the image
img_path = “../../data/sample-1.jpg”
img = Image.open(img_path)
img.show()
Preprocess the image
inputs = feature_extractor(images=img, return_tensors=”pt”)
Perform inference
outputs = model(**inputs)
Get logits and find the predicted class index
logits = outputs.logits
predicted_class_index = logits.argmax(-1).item()
predicted_label = model.config.id2label[predicted_class_index]
Extract the name of the food item
food_name = predicted_label.split(‘,’)[0]
Get nutritional information from the API
api_url = ‘https://api.api-ninjas.com/v1/nutrition?query={}’.format(food_name)
response = requests.get(api_url, headers={‘X-Api-Key’: secret_key})
Check the response status and print the response text
if response.status_code == requests.codes.ok:
print(response.text) # Print response text if the request was successful
else:
print(“Error:”, response.status_code, response.text) # Print error if the request failed
Why Use dotenv?
We use dotenv to securely manage environment variables:
- Environment Variables: Store sensitive information like model names and API keys securely.
- Security: Keeps your sensitive data out of your codebase, reducing the risk of exposing it accidentally.
Steps in the Code
- Import Libraries: Import necessary libraries like PIL for image handling, dotenv for environment variables, os for operating system interactions, requests for making API calls, and transformers for using the Vision Transformer model.
- Load Environment Variables: Use load_dotenv() to load the environment variables from a .env file. This includes the model name and API key.
- Load Pre-trained Model and Feature Extractor: Use ViTFeatureExtractor and ViTForImageClassification from the transformers library to load the pre-trained model and feature extractor.
- Load and Show Image: Load an image from the specified path and display it.
- Preprocess the Image: Use the feature extractor to preprocess the image and convert it into a format suitable for the model.
- Perform Inference: Run the model on the preprocessed image to get predictions.
- Get Predicted Class: Extract the predicted class from the model output.
- Extract Food Name: Extract the food name from the predicted label.
- Fetch Nutritional Information: Use the requests library to get nutritional information from the API based on the food name.
Check Response Status: Print the nutritional information if the API call is successful, otherwise print an error message.
Integrate with Gradio Server and Test
Imports
import gradio as gr
from transformers import ViTFeatureExtractor, ViTForImageClassification
from dotenv import load_dotenv
from PIL import Image
import os, requests
- gradio: This library helps create the web interface for uploading and processing images.
- transformers: Used to import the Vision Transformer model and feature extractor.
- dotenv: Loads environment variables from a .env file, which is useful for storing sensitive information like API keys.
- PIL: For opening and manipulating images.
- os, requests: os for interacting with the operating system, and requests for making HTTP requests to the nutrition API.
Loading Environment Variables
load_dotenv()
model_name = os.getenv(‘MODEL’) # Get the model name from environment variables
secret_key = os.getenv(‘API_KEY’) # Get the API key from environment variables
- load_dotenv(): Loads the variables from a .env file into the environment.
- model_name and secret_key: Retrieve the model name and API key from environment variables.
Loading the Model and Feature Extractor
feature_extractor = ViTFeatureExtractor.from_pretrained(model_name)
model = ViTForImageClassification.from_pretrained(model_name)
- feature_extractor: Initializes the feature extractor from the pre-trained model.
- model: Loads the pre-trained Vision Transformer model for image classification.
Identifying the Image
def identify_image(image_path):
“””Identify the food item in the image.”””
image = Image.open(image_path)
inputs = feature_extractor(images=image, return_tensors=”pt”)
outputs = model(**inputs)
logits = outputs.logits
predicted_class_idx = logits.argmax(-1).item()
predicted_label = model.config.id2label[predicted_class_idx]
food_name = predicted_label.split(‘,’)[0]
return food_name
- Image.open(image_path): Opens the image from the given path.
- inputs: Preprocesses the image and converts it to a format suitable for the model.
- outputs: Runs the model on the input image to get predictions.
- logits: The raw predictions from the model.
- predicted_class_idx: Index of the class with the highest prediction score.
- predicted_label: The label corresponding to the predicted class index.
- food_name: Extracts the food name from the predicted label.
Getting Calorie Information
def get_calories(food_name):
“””Get the calorie information of the identified food item.”””
api_url = f’https://api.api-ninjas.com/v1/nutrition?query={food_name}’
response = requests.get(api_url, headers={‘X-Api-Key’: secret_key})
if response.status_code == requests.codes.ok:
nutrition_info = response.json()
else:
nutrition_info = {“Error”: response.status_code, “Message”: response.text}
return nutrition_info
- api_url: Constructs the API URL using the food name.
- response: Sends a GET request to the API with the food name.
- nutrition_info: Parses the response. If successful, it contains the nutrition info, otherwise, it contains error details.
Formatting Nutritional Information
def format_nutrition_info(nutrition_info):
“””Format the nutritional information into an HTML table.”””
if “Error” in nutrition_info:
return f”Error: {nutrition_info[‘Error’]} – {nutrition_info[‘Message’]}”
if len(nutrition_info) == 0:
return “No nutritional information found.”
nutrition_data = nutrition_info[0]
table = f”””
<table border=”1″ style=”width: 100%; border-collapse: collapse;”>
<tr><th colspan=”4″ style=”text-align: center;”><b>Nutrition Facts</b></th></tr>
<tr><td colspan=”4″ style=”text-align: center;”><b>Food Name: {nutrition_data[‘name’]}</b></td></tr>
<tr>
<td style=”text-align: left;”><b>Calories</b></td><td style=”text-align: right;”>{nutrition_data[‘calories’]}</td>
<td style=”text-align: left;”><b>Serving Size (g)</b></td><td style=”text-align: right;”>{nutrition_data[‘serving_size_g’]}</td>
</tr>
<tr>
<td style=”text-align: left;”><b>Total Fat (g)</b></td><td style=”text-align: right;”>{nutrition_data[‘fat_total_g’]}</td>
<td style=”text-align: left;”><b>Saturated Fat (g)</b></td><td style=”text-align: right;”>{nutrition_data[‘fat_saturated_g’]}</td>
</tr>
<tr>
<td style=”text-align: left;”><b>Protein (g)</b></td><td style=”text-align: right;”>{nutrition_data[‘protein_g’]}</td>
<td style=”text-align: left;”><b>Sodium (mg)</b></td><td style=”text-align: right;”>{nutrition_data[‘sodium_mg’]}</td>
</tr>
<tr>
<td style=”text-align: left;”><b>Potassium (mg)</b></td><td style=”text-align: right;”>{nutrition_data[‘potassium_mg’]}</td>
<td style=”text-align: left;”><b>Cholesterol (mg)</b></td><td style=”text-align: right;”>{nutrition_data[‘cholesterol_mg’]}</td>
</tr>
<tr>
<td style=”text-align: left;”><b>Total Carbohydrates (g)</b></td><td style=”text-align: right;”>{nutrition_data[‘carbohydrates_total_g’]}</td>
<td style=”text-align: left;”><b>Fiber (g)</b></td><td style=”text-align: right;”>{nutrition_data[‘fiber_g’]}</td>
</tr>
<tr>
<td style=”text-align: left;”><b>Sugar (g)</b></td><td style=”text-align: right;”>{nutrition_data[‘sugar_g’]}</td>
<td></td><td></td>
</tr>
</table>
“””
return table
- Error Handling: Checks for errors in the nutrition information.
- No Info Handling: Checks if no nutritional information is found.
- HTML Table: Formats the nutrition data into an HTML table for display.
Main Processing Function
def main_process(image_path):
“””Identify the food item and fetch its calorie information.”””
food_name = identify_image(image_path)
nutrition_info = get_calories(food_name)
formatted_nutrition_info = format_nutrition_info(nutrition_info)
return formatted_nutrition_info
- food_name: Gets the food name by identifying the image.
- nutrition_info: Fetches the nutritional information using the food name.
- formatted_nutrition_info: Formats the nutritional information into an HTML table.
Gradio Interface Function
def gradio_interface(image):
formatted_nutrition_info = main_process(image)
return formatted_nutrition_info
- gradio_interface: This function will be called by Gradio when an image is uploaded. It runs the main processing function and returns the formatted nutrition info.
Creating the Gradio UI
iface = gr.Interface(
fn=gradio_interface,
inputs=gr.Image(type=”filepath”),
outputs=”html”,
title=”Food Identification and Nutrition Info”,
description=”Upload an image of food to get dummy nutritional information.”,
allow_flagging=”never” # Disable flagging
)
- iface: Defines the Gradio interface.
- fn: The function to call when an image is uploaded.
- inputs: The input type (an image file path).
- outputs: The output type (HTML).
- title: Title of the Gradio interface.
- description: Description of the Gradio interface.
- allow_flagging: Disables flagging of inappropriate content.
Launching the Gradio Interface
def launch_gradio():
iface.launch(share=True, server_name=”0.0.0.0″, server_port=7860)
if __name__ == “__main__”:
launch_gradio()
- launch_gradio(): Launches the Gradio interface, making it accessible from any device on the network (0.0.0.0) at port 7860. The share=True option generates a public link.
- if name == “main”: Ensures that the Gradio interface launches only when this script is run directly.
Integrate the Home Page and Test
Now this script integrates a Gradio interface with a Flask web application. When a user visits the homepage and chooses to “snap” a photo, they are redirected to the Gradio interface for food identification and nutritional information.
Imports and Setup
from flask import Flask, render_template, redirect, url_for
from src.main import launch_gradio
import threading
- flask: Flask is a lightweight web framework for Python. Flask is used to create the application, render_template to render HTML templates, redirect and url_for to handle URL redirection.
- launch_gradio: This is the function from the src.main module that launches the Gradio interface.
- threading: The threading module is used to run the Gradio server in a separate thread.
Flask Application Setup
app = Flask(__name__)
- app: Initializes the Flask application.
Home Route
python
Copy code
@app.route(‘/’)
def home():
return render_template(‘index.html’)
- @app.route(‘/’): Defines the route for the home page.
- home(): This function handles requests to the home page and renders the index.html template.
Snap Route
@app.route(‘/snap’)
def snap():
return redirect(‘http://127.0.0.1:7860’)
- @app.route(‘/snap’): Defines the route for the /snap URL.
- snap(): This function redirects the user to the Gradio interface running on http://127.0.0.1:7860.
Running Gradio in a Separate Thread
def run_gradio():
launch_gradio()
- run_gradio(): This function calls launch_gradio() to start the Gradio interface.
Main Block
if __name__ == ‘__main__’:
gradio_thread = threading.Thread(target=run_gradio)
gradio_thread.start()
app.run(debug=True, port=5000)
- if name == ‘main’: Ensures that this block of code runs only if the script is executed directly.
- gradio_thread = threading.Thread(target=run_gradio): Creates a new thread that will run the run_gradio function.
- gradio_thread.start(): Starts the Gradio server in the new thread.
- app.run(debug=True, port=5000): Starts the Flask web server on port 5000 with debug mode enabled.
Overall Flow
- Home Page: When a user accesses the root URL (/), the home function renders the index.html template.
- Snap Page: When a user accesses the /snap URL, the snap function redirects them to the Gradio interface running on http://127.0.0.1:7860.
- Gradio Server: The Gradio server is started in a separate thread by calling launch_gradio() inside the run_gradio function.
- Flask Server: The Flask server is started on port 5000.
This setup allows the Flask application to run concurrently with the Gradio interface, making it possible to navigate from the Flask home page to the Gradio interface seamless
Watch Full Video
Download Source Code
❤️ If you liked the article, like and subscribe to my channel, “Securnerd”.
👍 If you have any questions or if I would like to discuss the described hacking tools in more detail, then write in the comments. Your opinion is very important to me! at last of the post