Wednesday, December 4, 2024

DATA SCIENCE

 Using FastAPI for Building ML-Powered Web Apps

A beginner tutorial on building a simple web application for machine learning model inference using FastAPI and Jinja2 templates.
By Abid Ali Awan, KDnuggets Assistant Editor on September 5, 2024 in Python
FacebookTwitterLinkedInRedditEmailShare

Using FastAPI for Building ML-Powered Web Apps
Image by Author | Canva

 
In this tutorial, we will learn a little bit about FastAPI and use it to build an API for Machine Learning (ML) model inference. We will then use Jinja2 templates to create a proper web interface. This is a short but fun project that you can build on your own with limited knowledge about APIs and web development.




Our Top 3 Course Recommendations


 1. Google Cybersecurity Certificate - Get on the fast track to a career in cybersecurity.

 2. Google Data Analytics Professional Certificate - Up your data analytics game

 3. Google IT Support Professional Certificate - Support your organization in IT


 

What is FastAPI?
 

FastAPI is a popular and modern web framework used for building APIs with Python. It is designed to be fast and efficient, leveraging Python's standard type hints to provide the best development experience. It is easy to learn and requires only a few lines of code to develop high-performance APIs. FastAPI is widely used by companies such as Uber, Netflix, and Microsoft to build APIs and applications. Its design makes it particularly suitable for creating API endpoints for machine learning model inference and testing. We can even build a proper web application by integrating Jinja2 templates.

 

Model Training
 

We will train the Random Forest classifier on the most popular Iris dataset. After training is complete, we will display model evaluation metrics and save the model in pickle format.

train_model.py:

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report
import joblib

# Load the iris dataset
iris = load_iris()
X, y = iris.data, iris.target

# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

# Train a RandomForest classifier
clf = RandomForestClassifier(n_estimators=100, random_state=42)
clf.fit(X_train, y_train)

# Evaluate the model
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
report = classification_report(y_test, y_pred, target_names=iris.target_names)

print(f"Model Accuracy: {accuracy}")
print("Classification Report:")
print(report)

# Save the trained model to a file
joblib.dump(clf, "iris_model.pkl")
 

$ python train_model.py
 

Model Accuracy: 1.0
Classification Report:
              precision recall f1-score support

      setosa 1.00 1.00 1.00 10
  versicolor 1.00 1.00 1.00 9
   virginica 1.00 1.00 1.00 11

    accuracy 1.00 30
   macro avg 1.00 1.00 1.00 30
weighted avg 1.00 1.00 1.00 30
 

Building the ML API using the FastAPI
 

Next, we will install FastAPI and the Unicorn library, which we are going to use to build a model inference API. 

$ pip install fastapi uvicorn
 

In the `app.py` file, we will:

Load the saved model from the previous step.
Create the Python class for inputs and prediction. Make sure you specify the dtype. 
Then, we will create the predict function and use the `@app.post` decorator. The decorator defines a POST endpoint at the URL path `/predict`. The function will be executed when a client sends a POST request to this endpoint.
The predict function takes the values from the `IrisInput` class and returns them as the `IrisPrediction` class.
Run the app using the `uvicorn.run` function and provide it with the host IP and port number as shown below. 
app.py: 

from fastapi import FastAPI
from pydantic import BaseModel
import joblib
import numpy as np
from sklearn.datasets import load_iris

# Load the trained model
model = joblib.load("iris_model.pkl")

app = FastAPI()


class IrisInput(BaseModel):
    sepal_length: float
    sepal_width: float
    petal_length: float
    petal_width: float


class IrisPrediction(BaseModel):
    predicted_class: int
    predicted_class_name: str


@app.post("/predict", response_model=IrisPrediction)
def predict(data: IrisInput):
    # Convert the input data to a numpy array
    input_data = np.array(
        [[data.sepal_length, data.sepal_width, data.petal_length, data.petal_width]]
    )

    # Make a prediction
    predicted_class = model.predict(input_data)[0]
    predicted_class_name = load_iris().target_names[predicted_class]

    return IrisPrediction(
        predicted_class=predicted_class, predicted_class_name=predicted_class_name
    )


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="127.0.0.1", port=8000)
 

Run the Python file. 

$ python app.py
 

The FastAPI server is running, and we can access it by clicking on the link. 

INFO: Started server process [33828]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
 

It will take us to the browsers with the index page. We have nothing on the index page, just on the `/predict` POST request. That’s why nothing is shown. 

 
Using FastAPI for Building ML-Powered Web Apps
 
We can test our API by using the SwaggerUI interface. We can access it by adding “/docs” after the link.

 
Using FastAPI for Building ML-Powered Web Apps
 
We can click the “/predict” option, edit the value, and run the prediction. In the end, we will get the response in the response body section. As we can see, we got “Virginica” as a result. We can test our model with direct values within the SwaggerUI and ensure it is working properly before deploying it to production. 

 
Using FastAPI for Building ML-Powered Web Apps
 

Build a UI for the Web Application
 

Instead of using Swagger UI, we will create our own user interface that is simple and displays results like any other web application. To achieve this, we need to integrate Jinja2Templates within our app. Jinja2Templates allows us to build a proper web interface using HTML files, enabling us to customize various components of the webpage.

Initiate Jinja2Templates by providing it the directory where HTML files will be. 
Define an asynchronous route that serves the "index.html" template as an HTML response for the root URL ("/").
Making changes to the input argument of the `predict` function using Request and Form. 
Defines an asynchronous POST endpoint "/predict" that accepts form data for iris flower measurements, uses a machine learning model to predict the iris species, and returns the prediction results rendered in "result.html" using TemplateResponse.
The rest of the code is similar.
from fastapi import FastAPI, Request, Form
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
import joblib
import numpy as np
from sklearn.datasets import load_iris

# Load the trained model
model = joblib.load("iris_model.pkl")

# Initialize FastAPI
app = FastAPI()

# Set up templates
templates = Jinja2Templates(directory="templates")


# Pydantic models for input and output data
class IrisInput(BaseModel):
    sepal_length: float
    sepal_width: float
    petal_length: float
    petal_width: float


class IrisPrediction(BaseModel):
    predicted_class: int
    predicted_class_name: str


@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})


@app.post("/predict", response_model=IrisPrediction)
async def predict(
    request: Request,
    sepal_length: float = Form(...),
    sepal_width: float = Form(...),
    petal_length: float = Form(...),
    petal_width: float = Form(...),
):
    # Convert the input data to a numpy array
    input_data = np.array([[sepal_length, sepal_width, petal_length, petal_width]])

    # Make a prediction
    predicted_class = model.predict(input_data)[0]
    predicted_class_name = load_iris().target_names[predicted_class]

    return templates.TemplateResponse(
        "result.html",
        {
            "request": request,
            "predicted_class": predicted_class,
            "predicted_class_name": predicted_class_name,
            "sepal_length": sepal_length,
            "sepal_width": sepal_width,
            "petal_length": petal_length,
            "petal_width": petal_width,
        },
    )


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="127.0.0.1", port=8000)
 

Next, we will create a directory named `templates` in the same directory as `app.py`. Inside the `templates` directory, create two HTML files: `index.html` and `result.html`.

If you are a web developer, you will easily understand the HTML code. For beginners, I will explain what is happening. This HTML code creates a web page with a form for predicting iris flower species. It allows users to input "Sepal" and "Petal" measurements and submit them via a POST request to the "/predict" endpoint.

index.html:

<!DOCTYPE html>

<html>

<head>

<title>Iris Flower Prediction</title>

</head>

<body>

<h1>Predict Iris Flower Species</h1>

<form action="/predict" method="post">

<label for="sepal_length">Sepal Length:</label>

<input type="number" step="any" id="sepal_length" name="sepal_length" required><br>

<label for="sepal_width">Sepal Width:</label>

<input type="number" step="any" id="sepal_width" name="sepal_width" required><br>

<label for="petal_length">Petal Length:</label>

<input type="number" step="any" id="petal_length" name="petal_length" required><br>

<label for="petal_width">Petal Width:</label>

<input type="number" step="any" id="petal_width" name="petal_width" required><br>

<button type="submit">Predict</button>

</form>

</body>

</html>
 

The `result.html` code defines a web page that displays the prediction results, showing the inputted sepal and petal measurements and the predicted iris species. It also displays the prediction class name with class ID and has a button that will take you to the index page. 

result.html:

<!DOCTYPE html>

<html>

<head>

<title>Prediction Result</title>

</head>

<body>

<h1>Prediction Result</h1>

<p>Sepal Length: {{ sepal_length }}</p>

<p>Sepal Width: {{ sepal_width }}</p>

<p>Petal Length: {{ petal_length }}</p>

<p>Petal Width: {{ petal_width }}</p>

<h2>Predicted Class: {{ predicted_class_name }} (Class ID: {{ predicted_class }})</h2>

<a href="/">Predict Again</a>

</body>

</html>
 

Run the Python app file again. 

$ python app.py 
 

INFO: Started server process [2932]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: 127.0.0.1:63153 - "GET / HTTP/1.1" 200 OK
 

When you click on the link, you won't see the empty screen; instead, you will see the user interface where you can enter the "Sepal" and "Petal" length and width. 

 
Using FastAPI for Building ML-Powered Web Apps
After clicking the "Predict" button, you will be taken to the next page, where the results will be displayed. You can click on the "Predict Again" button to test your model with different values.

 
Using FastAPI for Building ML-Powered Web Apps
 
All the source code, data, model, and information are available at the kingabzpro/FastAPI-for-ML GitHub repository. Please don't forget to star ⭐ it.

 

Conclusion
 

Many large companies are now using FastAPI to create endpoints for their models, allowing them to deploy and integrate these models seamlessly across their systems. FastAPI is fast, easy to code, and comes with a variety of features that meet the demands of the modern data stack. The key to landing a job in this area is to build and document as many projects as possible. This will help you gain the experience and knowledge necessary for the initial screening sessions. Recruiters will evaluate your profile and portfolio to determine if you are a good fit for their team. So, why not start building projects using FastAPI today?
 
 

Abid Ali Awan (@1abidaliawan) is a certified data scientist professional who loves building machine learning models. Currently, he is focusing on content creation and writing technical blogs on machine learning and data science technologies. Abid holds a Master's degree in technology management and a bachelor's degree in telecommunication engineering. His vision is to build an AI product using a graph neural network for students struggling with mental illness.


More On This Topic
Meet MetaGPT: The ChatGPT-Powered AI Assistant That Turns Text Into…
Building Data Pipelines to Create Apps with Large Language Models
Beginner’s Guide to Building LLM Apps with Python
A Beginner’s Guide to Web Scraping Using Python
FastAPI Tutorial: Build APIs with Python in Minutes
Python Vector Databases and Vector Indexes: Architecting LLM Apps


Monday, August 26, 2024

Wirecard goes down with dues worth $4 billion

 


Markus Braun,wirecard,wirecard ceo,wirecard Markus Braun,wirecard scame

In the tech industry at large, companies are gravitated towards new technologies, for any one of them can be the next Paypal or Facebook. And thus, when a scam breaks out, the numbers involved are usually mind boggling. That being said, Wirecard, the infamous payments company whose CEO is involved in perhaps tech world’s biggest scam, is going down, owing close to $4 billion to creditors.


The company had been leading down a dark path for some time now. It all started last year, when a series of reports in British newspaper Financial Times uncovered accounting irregularities in its Asian operations.


Then, things took a turn for the worse when EY, the company’s auditor for more than a decade, refused to sign off the 2019 accounts last week. EY explains that during the audits, it was provided with false confirmations with regard to escrow accounts and reported them to the relevant authorities. Wirecard, being guilty as it was, did not comment. And honestly, how can you when you are planning to pull off the fraud of the decade?


“There are clear indications that this was an elaborate and sophisticated fraud involving multiple parties around the world,” EY said in a statement.


In fact, Chief Executive Markus Braun was forced to admit that $2.1 billion of the company’s cash probably didn’t exist. He has been detained under the suspicions of inflating the company’s value by showing assets that he did not own.


The $2.1 billion in question was supposed to have been held by two banks in the Philippines. However, it was found last week that the money did not even enter the financial system of the country’s central bank.


The company’s shares tanked after the announcement. And by tanked, I mean a gargantuan 98% fall. The only option left for Wirecard was to file for insolvency, which it did. The company said that with 1.3 billion euros ($1.5 billion) of loans due within a week, its survival as a going concern was “not assured”.


Now, the money is gone. Yeah, that’s a cynical view of seeing it, but that’s the truth, according to Reuters, which has spoken with people familiar with the matter. Over the years, the creditors might see some dollars returning to their accounts, but for the most part, the $4 billion is gone.


German law firm Schirp & Partner said that they would file class action lawsuits against EY, the auditor which let Wirecard’s shady numbers pass for years.


“It is frightening how long Wirecard AG was able to operate without being objected to by the auditors,” partner Wolfgang Schirp said.

Sunday, August 25, 2024

CYBER SECURITY

 Microsoft to host cybersecurity summit after CrowdStrike-induced IT outage

By Reuters



Aug 23 (Reuters) - Microsoft (MSFT.O), opens new tab said on Friday it would hold a summit in September to discuss steps to improve cybersecurity systems, after a faulty update from CrowdStrike (CRWD.O), opens new tab caused a global IT outage last month.

The conference marks the first big step by Microsoft to address the issues that affected nearly 8.5 million Windows devices on July 19, disrupting operations across industries ranging from major airlines to banks and healthcare.

The event will be held on Sept. 10 at Microsoft's headquarters in Redmond, Washington. The company will invite government representatives to the gathering, it said in a blog.

"The CrowdStrike outage in July presents important lessons for us to apply as an ecosystem," Microsoft said.

The outage raised concerns that many organizations are not well prepared to implement contingency plans when a single point of failure such as an IT system, or a piece of software within it, goes down.
"We look forward to bringing our perspective to the discussions with Microsoft and industry and government stakeholders on the need for a more resilient ecosystem," a CrowdStrike spokesperson said when contacted for a comment.

Analysts have said the outage has exposed risks of dependence on single-vendor providing one-stop shop for security solutions.

CrowdStrike, which has lost about $9 billion of its market value since the outage, has been sued by shareholders, who said the cybersecurity company defrauded them by concealing how its inadequate software testing could cause the global disruption.
Earlier this month, Delta Air Lines (DAL.N), opens new tab said it was pursuing legal claims against CrowdStrike and Microsoft, after the outage caused mass flight cancellations and cost the carrier at least $500 million.

CrowdStrike is scheduled to report its second-quarter financial results after the U.S. market close on Aug. 28.

CYBER SECURITY

 Meta says Iranian group tried to target Trump, Biden officials' WhatsApp accounts.


Aug 23 - Meta (META.O), opens new tab said on Friday it had identified possible hacking attempts on the WhatsApp accounts of U.S. officials from the administrations of both President Joe Biden and former President Donald Trump, blaming the same Iranian hacker group revealed earlier this month to have compromised the Trump campaign.
In a blog post, the parent company of Facebook, Instagram and WhatsApp described the attempt as a "small cluster of likely social engineering activity on WhatsApp" involving accounts posing as technical support for AOL, Google, Yahoo and Microsoft.

It blocked the accounts after users reported the activity as suspicious and had not seen any evidence suggesting the targeted WhatsApp accounts had been compromised, it said.

Meta attributed the activity to APT42, a hacking group widely believed to be associated with an intelligence division inside Iran's military that is known for placing surveillance software on the mobile phones of its victims. The software enables the team to record calls, steal text messages and silently turn on cameras and microphones, according to researchers who follow the group.

It linked the group's activity to efforts to breach U.S. presidential campaigns reported by Microsoft and Google earlier this month, ahead of the U.S. presidential election in November.

The company's blog post did not name the individuals targeted, saying only that the hackers "appeared to have focused on political and diplomatic officials, business and other public figures, including some associated with administrations of President Biden and former President Trump."

Those figures were based in Israel, the Palestinian territories, Iran, the United States and the United Kingdom, it added.

Telegram messaging app CEO Durov arrested in France

By Ingrid Melander and Guy Faulconbridge


Durov arrested in Bourget airport, police sources say

•Telegram is based in Dubai

•Durov has French and UAE citizenship

•Russia says Durov's rights should be respected

•Russian lawmaker: freedom of speech is dead in Europe

PARIS/MOSCOW, Aug 25 (Reuters) - Pavel Durov, the Russian-born billionaire founder and owner of the Telegram messaging app, was arrested at Le Bourget airport outside Paris shortly after landing on a private jet late on Saturday and placed in custody, three sources told Reuters.

The arrest of the 39-year-old technology billionaire prompted on Sunday a warning from Moscow to Paris that he should be accorded his rights and criticism from X owner Elon Musk who said that free speech in Europe was under attack.

There was no official confirmation from France of the arrest, but two French police sources and one Russian source who spoke on condition of anonymity said that Durov was arrested shortly after arriving at Le Bourget airport on a private jet from Azerbaijan.

One of the two French police sources said that ahead of the jet's arrival police had spotted he was on the passenger list and moved to arrest him because he was the subject of an arrest warrant in France.

Durov, who has dual French and United Arab Emirates citizenship, was arrested as part of a preliminary police investigation into allegedly allowing a wide range of crimes due to a lack of moderators on Telegram and a lack of cooperation with police, a third French police source said.

A cybersecurity gendarmerie unit and France's national anti-fraud police unit are leading the investigation, that source said, adding that the investigative judge was specialised in organised crime.

Telegram and senior Telegram managers did not respond to repeated requests for comment. The French Interior Ministry, police and Paris prosecutor's office had no comment. Durov faces possible indictment on Sunday, according to French media.

Russian lawmaker Maria Butina, who spent 15 months in U.S. prison for acting as an unregistered Russian agent, said Durov "is a political prisoner - a victim of a witch-hunt by the West." Durov's arrest led news bulletins in Russia.

Telegram, based in Dubai, was founded by Durov, who left Russia in 2014 after he refused to comply with demands to shut down opposition communities on his VK social media platform, which he has sold.

The encrypted application, with close to one billion users, is particularly influential in Russia, Ukraine and the republics of the former Soviet Union. It is ranked as one of the major social media platforms after Facebook, YouTube, WhatsApp, Instagram, TikTok and WeChat.

TELEGRAM

Durov, who is estimated by Forbes to have a fortune of $15.5 billion, said in April some governments had sought to pressure him but the app should remain a "neutral platform" and not a "player in geopolitics".

Durov came up with the idea of an encrypted messaging app as a way to communicate while he faced pressure in Russia. His younger brother, Nikolai, designed the encryption.

"I would rather be free than to take orders from anyone," Durov said in April about his exit from Russia and search for a home for his company which included stints in Berlin, London, Singapore a

nd San Francisco.



After Russia launched its invasion of Ukraine in 2022, Telegram has become the main source of unfiltered - and sometimes graphic and misleading - content from both sides about the war and the politics surrounding the conflict.

The platform has become what some analysts call 'a virtual battlefield' for the war, used heavily by Ukraine's President Volodymyr Zelenskiy and his officials, as well as the Russian government.

Russia's foreign ministry said it had sent a note to Paris demanding access to Durov, although it said that he had French citizenship.

Former Russian President Dmitry Medvedev said that Durov had misjudged by fleeing Russia and thinking that he would never have to cooperate with the security services abroad.

Medvedev, who regularly uses Telegram to criticise and insult the West, said Durov wanted to be a "brilliant 'man of the world' who lives wonderfully without a Motherland."

"He miscalculated," Medvedev said. "For all our common enemies now, he is Russian – and therefore unpredictable and dangerous."

Russia began blocking Telegram in 2018 after the app refused to comply with a court order granting state security services access to its users' encrypted messages.

The action interrupted many third-party services, but had little effect on the availability of Telegram there. The ban order, however, sparked mass protests in Moscow and criticism from NGOs.

'NEUTRAL PLATFORM'

Telegram says it "is committed to protecting user privacy and human rights such as freedom of speech and assembly."

Durov has previously accused U.S. law enforcement agencies such as the Federal Bureau of Investigation (FBI) of seeking to get a backdoor into the platform. The FBI has not commented on those allegations.

Telegram's increasing popularity, however, has prompted scrutiny from several countries in Europe, including France, on security and data breach concerns.

Musk, billionaire owner of X, the social media platform formerly known as Twitter, said after reports of Durov's detention: "It's 2030 in Europe and you’re being executed for liking a meme."

Outside the French embassy in Moscow, a lone protester held up a sign reading: "Liberté pour Pavel Durov".

(This story has been refiled to fix a grammar in the first bullet point)

DATA SCIENCE

 Using FastAPI for Building ML-Powered Web Apps A beginner tutorial on building a simple web application for machine learning model inferenc...