
(4.8-launching-free-cloud-server)=
# 🧩 4.8 Launching a Free Cloud Server

```{contents}
:depth: 3
```

## 🔰 Tutorial

In this module, you will learn how to launch a free cloud server, leverage **serverless computing**, and deploy applications using **PythonAnywhere** and **Hugging Face**. By the end of this module, you'll be able to:

1. Launch a free cloud server
2. Use a container to deploy applications
3. Create a container for your app
4. Deploy a materials discovery campaign on a cloud server

### Launching a Free Cloud Server

A cloud server is a virtual server that you can access over the internet. Many cloud platforms offer free tiers for users to launch servers, allowing you to run and deploy your applications in the cloud without incurring costs.

#### Free Cloud Server Providers:
1. **PythonAnywhere**: A Python-centric cloud platform that offers a free plan with enough resources for small-scale applications.
2. **Google Cloud Platform (GCP)**: Provides free credits and the option to launch a small virtual machine for free.
3. **AWS Free Tier**: Offers free EC2 instances for the first 12 months.
4. **Hugging Face Spaces**: Provides a free option to deploy machine learning models and web applications using the Gradio or Streamlit framework.

#### Steps to Launch a Free Cloud Server on PythonAnywhere:

1. **Sign up for PythonAnywhere**:
   Go to [PythonAnywhere](https://www.pythonanywhere.com) and create a free account.

2. **Start a New Console**:
   Once logged in, go to the **Consoles** tab and start a new **Bash** console.

3. **Set Up Your Application**:
   You can set up your Python environment and install necessary packages:
   ```bash
   pip install -r requirements.txt
   ```

4. **Deploy Your Application**:
   You can deploy web apps or Python scripts directly by using the **Web** tab to set up a web application or schedule your scripts to run.

**Video Tutorial**: [PythonAnywhere Overview](https://www.youtube.com/watch?v=yhqYFyo7dAM&pp=ygUOUHl0aG9uQW55d2hlcmU%3D)

### Serverless Computing

**Serverless computing** allows you to run your code without having to manage the underlying infrastructure. You only pay for the compute resources when your code is executed, making it ideal for small-scale or on-demand applications.

#### Benefits of Serverless Computing:
1. **Cost Efficiency**: You are only billed for actual compute time, rather than for server uptime.
2. **Scalability**: Serverless platforms can automatically scale your application based on demand.
3. **Ease of Use**: You don't need to manage or configure the server, allowing you to focus on application development.

#### Popular Serverless Platforms:

1. **AWS Lambda**: Executes your code in response to events (such as HTTP requests or file uploads) without requiring you to provision or manage servers. AWS Lambda automatically scales your application by running code in response to each trigger, making it highly reliable and cost-effective for event-driven workloads.

2. **Google Cloud Functions**: A lightweight, event-driven serverless compute platform similar to AWS Lambda. It's great for tasks like executing code in response to HTTP requests, Cloud Storage events, or Pub/Sub messages. It’s well integrated with other Google Cloud services and offers seamless scalability.

3. **Azure Functions**: Microsoft's serverless platform that also supports event-driven execution, with deep integration into the Azure ecosystem. It supports a wide range of triggers (e.g., HTTP requests, queue messages) and can be used to execute code in response to changes in Azure Storage or Cosmos DB, making it ideal for cloud-native applications running on Azure.

4. **Hugging Face Spaces**: A serverless platform specifically designed for deploying machine learning models and web applications. Hugging Face Spaces supports frameworks like Gradio and Streamlit, which makes it easy to deploy and share ML-powered applications with others.

### Using Containers

**Containers** provide a consistent environment for your applications, making it easier to deploy them across different systems, including cloud servers. A container includes everything your application needs to run, such as libraries, dependencies, and configuration files.

To better understand what a container does, think of it as a **pizza box**. Just as a pizza box holds and protects a pizza, allowing it to be transported anywhere while keeping the pizza intact, a container holds your application and its environment, ensuring that the app can run anywhere without changes—whether on your local machine, a colleague’s system, or a cloud server.

#### Steps to Use a Container:
1. **Install Docker**:
   Docker is the most widely used container platform. Install Docker on your local machine:

   ```bash
   sudo apt-get update
   sudo apt-get install docker-ce docker-ce-cli containerd.io
   ```

2. **Create a Dockerfile**:
   A Dockerfile is a text file that contains instructions for building a Docker image. Here’s an example Dockerfile for a Python Flask app:

   ```dockerfile
   # Use an official Python runtime as a parent image
   FROM python:3.8-slim

   # Set the working directory
   WORKDIR /app

   # Copy the current directory contents into the container at /app
   COPY . /app

   # Install any needed packages specified in requirements.txt
   RUN pip install --no-cache-dir -r requirements.txt

   # Make port 5000 available to the world outside this container
   EXPOSE 5000

   # Run app.py when the container launches
   CMD ["python", "app.py"]
   ```

3. **Build the Docker Image**:
   Run the following command to build your Docker image:

   ```bash
   docker build -t my_flask_app .
   ```

4. **Run the Container**:
   After building the image, you can run the container:

   ```bash
   docker run -p 5000:5000 my_flask_app
   ```

**Video Tutorial**: [Getting Started with Docker](https://www.youtube.com/watch?v=fqMOX6JJhGo)

### Creating a Container

Containers are useful for creating reproducible environments that work on any cloud platform or local machine. You can define all dependencies and settings in a container, ensuring that your application will run smoothly, regardless of the environment.

#### Steps to Create a Container for Your App:

1. **Create a Dockerfile**:
   Create a `Dockerfile` in your project directory that includes the necessary instructions for your application (see the Dockerfile example above).

2. **Build the Image**:
   Use the `docker build` command to build your image from the Dockerfile.

3. **Test Locally**:
   Before deploying your container to the cloud, run it locally to ensure that everything works as expected.

**Video Tutorial**: [Build Your Own Container](https://www.youtube.com/watch?v=SnSH8Ht3MIc&ab_channel=TechnoTim)

### Deploying a Materials Discovery Campaign on a Cloud Server

In this example, we will deploy a simplified **materials discovery campaign** where the goal is to analyze a dataset of material properties (e.g., conductivity, hardness, and thermal resistance) and predict optimal materials for specific applications. We will deploy this application on a cloud server, enabling users to submit data and receive predictions from a trained machine learning model hosted in the cloud.

#### Steps to Deploy a Materials Discovery Campaign:

1. **Dataset Preparation**:
   The campaign starts by loading a dataset of materials with their respective properties. The dataset could be a CSV file containing columns like `Material Name`, `Conductivity`, `Hardness`, and `Thermal Resistance`.

2. **Model Training**:
   Train a machine learning model (e.g., a Random Forest or Neural Network) that can predict the best material for a given set of conditions (e.g., optimal material for high conductivity and low thermal resistance). Save the trained model as a `.pkl` file.

3. **Create a Flask Application**:
   Develop a Python Flask application that will serve as the front-end for the campaign. Users can submit material properties through a web form, and the model will return a prediction of the best material.

   ```python
   from flask import Flask, request, jsonify
   import pickle

   app = Flask(__name__)

   # Load the trained model
   with open("model.pkl", "rb") as f:
       model = pickle.load(f)


   @app.route("/predict", methods=["POST"])
   def predict():
       data = request.json
       prediction = model.predict([data["properties"]])
       return jsonify({"predicted_material": prediction[0]})


   if __name__ == "__main__":
       app.run(debug=True)
   ```

4. **Containerize the Application**:
   Use Docker to containerize the Flask application (refer to the Dockerfile example above).

5. **Deploy the Application**:
   Deploy the containerized application on PythonAnywhere or Hugging Face Spaces. Ensure the web interface is accessible and that users can submit data and receive predictions in real-time.

**Video Tutorial**: [Flask Deploy to Huggingface Cloud](https://youtu.be/pWnE9FHnGcQ)

### Additional Resources

- [PythonAnywhere Documentation](https://help.pythonanywhere.com/pages/)
- [Hugging Face Spaces Documentation](https://huggingface.co/docs)
- [Docker Documentation](https://docs.docker.com/)
- [Serverless Framework Documentation](https://www.serverless.com/framework/docs/)

## 🚀 Quiz

::::{tab-set}
:sync-group: category

:::{tab-item} W 2024
:sync: w2024

:::

:::{tab-item} Sp/Su 2024
:sync: sp2024

https://q.utoronto.ca/courses/370070/assignments/1393631?display=full_width
:::

:::{tab-item} Sp/Su 2025
:sync: sp2025

https://q.utoronto.ca/courses/393352/assignments/1499735?display=full_width_with_nav
:::

::::

## 📄 Assignment

::::{tab-set}
:sync-group: category

:::{tab-item} W 2024
:sync: w2024

:::

:::{tab-item} Sp/Su 2024
:sync: sp2024

https://q.utoronto.ca/courses/370070/assignments/1394238?display=full_width
:::

:::{tab-item} Sp/Su 2025
:sync: sp2025

https://q.utoronto.ca/courses/393352/assignments/1499736?display=full_width_with_nav
:::

::::
