In today’s data-driven world, understanding the sentiment behind some text is crucial for making informed decisions. By sentiment analysis we mean working out whether tone the writer was using in their text could be categorized as angry, happy, sad, enthusiastic and so on. Imagine a powerful desktop application that instantly classifies text as neutral, positive, or negative. A feedback form handler, for example, which can tell if customers are angry about something. Or a review tool for a restaurant chain which can see automatically if their clientele is mostly happy with the service and food quality. We can turn this vision into reality with the Python Delphi ecosystem and the advanced deep-learning models from Hugging Face.
In this article, we’ll explore the fusion of Delphi’s development process and the precision of deep learning. By leveraging the flexibility of Delphi’s FMX framework, we’ll create an intuitive user interface, complete with a file picker and text input, enabling users to analyze sentiment effortlessly. And to take our app to the next level, we’ll enrich the user experience and provide an understanding of the analyzed text.
Table of Contents
Why Have Transformers Become Popular in Deep Learning?
Transformers have become widely popular in sentiment analysis apps due to their groundbreaking impact on natural language processing (NLP). With their attention mechanism, transformers excel at capturing contextual relationships within the text, enabling more accurate sentiment analysis by capturing subtle nuances and dependencies.
Moreover, transformers have revolutionized transfer learning in sentiment analysis. Developers can leverage comprehensive language representations by pre-training models on extensive datasets and fine-tuning them on sentiment-specific tasks, saving valuable time and resources. This approach has significantly accelerated the development process of sentiment analysis apps, enabling them to decipher sentiments in a context-aware manner accurately.
Which Tools Can Be Used For Creating GUIs for ML-Powered Apps?
When creating GUIs for ML-powered apps, the Delphi IDE and Delphi FMX (FireMonkey) framework are powerful tools at your disposal.
The Delphi IDE provides a comprehensive set of visual design tools and components that enable you to create stunning and intuitive user interfaces for your ML-powered applications. With its drag-and-drop interface, you can easily design and customize GUI elements, such as buttons, input fields, and data displays, to create a seamless user experience.
The Delphi FMX framework is a cross-platform UI framework that allows you to build visually appealing and responsive user interfaces. FMX supports multiple platforms, including Windows, macOS, Android, and iOS, making it suitable for creating ML-powered apps that can be deployed on different devices.
Furthermore, if you’re working with ML models developed in Python, you can leverage the Delphi4PythonExporter tool. This tool seamlessly integrates Delphi and Python, allowing you to export and utilize your Python-based ML models within your Delphi application.
How to Create a Sentiment Analysis App With a Stunning GUI for Desktop?
What Are the Prerequisites For Creating A Sentiment Analysis App?
To create a sentiment analysis app, specific prerequisites need to be met. Install Delphi IDE and the FMX Python library on your device. These tools will provide the foundation for developing the app’s graphical user interface. You will also require a text editor or IDE that supports Python, such as PyScripter, along with the Delphi4PythonExporter tool for seamless integration between Delphi and Python.
If any of these tools are not yet installed, it is recommended to refer to the article titled “Powerful Python GUI Project Setup” to assist you in getting started. In terms of Python libraries, the transformers library is essential for working with pre-trained models and performing sentiment analysis tasks. You can install this library by executing the following command:
1 2 |
pip install transformers |
Finally, to access the code for this tutorial, you can retrieve it from the GitHub repository provided below:
https://github.com/Embarcadero/PythonBlogExamples/tree/main/Sentiment_Analysis_App
Can I Download Pre-trained Sentiment Analysis Models From Online Platforms?
Yes, you can download pre-trained models from online platforms, and one popular platform for accessing and downloading pre-trained models is Hugging Face. This platform provides a wide range of pre-trained models for various NLP tasks, including sentiment analysis, text classification, machine translation, question answering, and more. These models are trained on large datasets and have already learned language representations, making them valuable resources for building NLP applications.
To download pre-trained models from Hugging Face, you can use their Python library called “transformers.” This library lets you easily access and utilize pre-trained models in your machine-learning projects. You can select a specific model based on your task requirements, such as sentiment analysis, and then download the model files and the associated tokenizer.
Once downloaded, you can use the pre-trained model in your ML pipeline, fine-tune it on your specific dataset, or integrate it into your ML-powered app using frameworks like PyTorch or TensorFlow.
How to Create a Stunning GUI For Our Sentiment Analysis App?
Let’s start by opening up Delphi CE and creating a blank project. We will do this by selecting Multi-Device Application > Blank Application
and clicking Ok. Here, we have named our project as Sentiment_Analysis_App
.
If you need to become more familiar with the various sections of the Delphi IDE, we recommend referring to our free eBook bundle, which covers the Delphi Python EcoSystem and all Python GUI offerings.
Let’s start by renaming our form. To do this, right-click on the form and select QuickEdit. Here we will name our form MainForm
with the caption Sentiment Analysis App
.
Next, we will rename our source file from Unit1.pas
to Main.pas
to make it easier to keep track of.
Now, we will resize our form. To do this, select the form and navigate to the Object Inspector. Here we will search for the ClientWidth
and ClientHeight
properties in the Properties tab. We will set these properties to 500
and 500
, respectively.
Now let’s start adding a few labels to our form. To do this, navigate to the standard Palette and search for the TLabel
component. Drag and drop this component onto the form.
Now modify the style by using the TextSettings
property of the label. We will do this by navigating to the Object Inspector
and searching for the TextSettings
property. Next, click the ellipses button next to the Font
property to see options for modifying the label based on your preferences. Here we will set our font family as SemiBold Segoe UI with different font sizes for each label. In addition, we will set the HorzAlign
and VertAlign
properties for our labels as Center
.
Here is what our form looks like:
As you can see in the form, we have added three labels to our form. The Title
label will serve only as a placeholder to display the title. The Result
label will show the result of the sentiment analysis algorithm. Finally, the FileName
label will simply display the filename.
Next, let’s add a few buttons to our form. For this, we will use the TButton
component, so navigate to the Palette and search for the component.
We will add two buttons to our form. The ResultButton
will evaluate the sentiment of our input, whereas the FilePickButton
will help us select a file that will be analyzed.
We have also disabled the FilePickButton
by default by setting the Enabled
property to False
.
To allow the user to select a file, we will add a TOpenDialog
component, which will help us open a dialog box to select a file from our system. So open up the Palette and search for the TOpenDialog
component. Drag and drop this component anywhere on your form.
Now, let’s add a text box to our form to allow the user to input some text the model will analyze. To do this, open up the Palette and search for TEdit
. Add this component to your form and rename it to SentimentTextEdit
.
Turn off this button by setting the Enabled
property to False
.
To complete our form, we will add a few TRadioButton
components. These will help the user select the file picker or the text box to analyze some text. So open up the Palette and search for the TRadioButton
component. Add this component to your form. We will add two radio buttons FilePickerRadio
, and TextboxRadio
, that will help us select either of them. Here is what our form looks like:
How to Create Stylish Forms in Delphi IDE?
Now that our form is ready, let’s add some style. But before that, you will need to download the free ebook bundle, which comes shipped with a multitude of styles that you can choose from.
First, download your free ebook and extract the FMX styles zip to your chosen directory. Next, select the style you want to use. For this project, we will use AquaGraphite.style
available in the bundle.
To use this style, head to the Palette and add the TStyleBook
component to your form.
Next, double-click on the StyleBook1
component to open up your Style Designer. Now, click on the open button to open up a dialog box.
Navigate to the .style
file of your choosing in the dialog box, select your file, and finally click on exit.
Once you’ve finalized your style, select the MainForm and head to the Object Inspector. Here we will search for the StyleBook property. Select the drop-down menu and select StyleBook1.
Here is what our form looks like:
Let’s complete our form by adding an image. Start by making some room for our image. We will move all the components down by a few pixels for this. Next, head over to the Palette and search for the TImage
component. Add this component to your form.
Next, head to the object inspector and click on the ellipses (...
) next to the MultiResBitMap
property.
Click on the Fill All From File
button and select your chosen image. Now Click on the exit button to load the image.
Finally, adjust the image to your needs. Here is what our final form looks like:
Can I Export These Forms to Python Code?
Now that the form is complete, we can export it using the Delphi4Python exporter. But before we can do that, we need to add some functionality to each button in the form.
To do this, double-click on each button on the form. This will add an OnClick
method to that button. The procedure will be created in the .pas
file of the form. This allows you to add unique functionality to each button when clicked.
Because the Delphi4PythonExporter does not use run-time implementation, we must add at least one comment (//
) to each procedure to preserve the function when we export the form.
Now that our form is ready, we are ready to export. Select Tools > Export To Python > Export Current Entire Project
to export the project.
Here we will give the project the title Sentiment Analysis App
. Next, select the directory of your choosing and click on Export:
Because we had one form, Delphi will generate two Python files and one .pyfmx
file.The Sentiment_Analysis_App.py
file will be used to run the application, whereas the Main.py
file contains the class for the MainForm
. The .pyfmx
file contains the visual information for the MainForm
. Below are the contents for each Python file.
Sentiment_Analysis_App.py:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
from delphifmx import * from Main import MainForm def main(): Application.Initialize() Application.Title = 'Sentiment Analysis App' Application.MainForm = MainForm(Application) Application.MainForm.Show() Application.Run() Application.MainForm.Destroy() if __name__ == '__main__': main() |
Main.py:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import os from delphifmx import * class MainForm(Form): def __init__(self, owner): self.Title = None self.Result = None self.FileName = None self.FilePickButton = None self.ResultButton = None self.OpenDialog1 = None self.SentimentTextEdit = None self.TextboxRadio = None self.FilePickerRadio = None self.Image1 = None self.StyleBook1 = None self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx")) def FilePickButtonClick(self, Sender): pass def ResultButtonClick(self, Sender): pass |
How to Put it All Together Into a Full-Fledged Sentiment Analysis App?
Now that we are done with the form, all we need to do is add functionality. Let’s start by opening up Main.py
in the text editor of your choice and importing some libraries:
1 2 3 |
# Additional imports from transformers import AutoTokenizer, AutoModelForSequenceClassification |
Next, head over to the __init__
function and initialize the model and tokenizer for the transformer model. Here we will use the "ProsusAI/finbert"
sentiment analyzer model available on HuggingFace. Here is what our final __init__
function looks like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
def __init__(self, owner): self.Title = None self.Result = None self.FileName = None self.FilePickButton = None self.ResultButton = None self.OpenDialog1 = None self.SentimentTextEdit = None self.TextboxRadio = None self.FilePickerRadio = None self.Image1 = None self.StyleBook1 = None self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx")) # Initialize model and tokenizer self.tokenizer = AutoTokenizer.from_pretrained("ProsusAI/finbert") self.model = AutoModelForSequenceClassification.from_pretrained("ProsusAI/finbert") |
Next, navigate to the FilePickButtonClick
function. Here we will open the file picker dialog box and filter the files to show only the .txt
files. Our final FilePickButtonClick
function looks like:
1 2 3 4 5 6 7 8 9 |
def FilePickButtonClick(self, Sender): self.OpenDialog1.Title = "Select an Image" # Filtering only image formats to show self.OpenDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*" if self.OpenDialog1.Execute(): self.FileName.Text = "Filename: " + os.path.basename(self.OpenDialog1.FileName) |
Now, let’s define our ResultButtonClick
function. We will start by checking which radio button is checked. If the TextboxRadio
button is checked, we will extract the text from the SentimentTextEdit
text box and store it in our text
variable. We will then use our predict
function (which we will define later) to predict the sentiment of the text. The predict
function will also display the sentiment in the Result
label:
1 2 3 4 5 6 |
def ResultButtonClick(self, Sender): if self.TextboxRadio.IsChecked: text = self.SentimentTextEdit.Text print(text) self.predict(text) |
Next, if the FilePickerRadio
button is checked, we open the text file and store the data in the text
variable. We then use the predict
function to predict the sentiment. Our final ResultButtonClick
function looks like:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
def ResultButtonClick(self, Sender): if self.TextboxRadio.IsChecked: text = self.SentimentTextEdit.Text print(text) self.predict(text) elif self.FilePickerRadio.IsChecked: with open(self.OpenDialog1.FileName, 'r') as file: text = file.read() print(text) self.predict(text) else: pass |
Now, let’s define our predict
function. We will start by processing our text to generate tokens
. We will then pass these tokens to the model to generate an output based on the text. We then extract the output from the last layer of the model to get the predicted_label
. Next, we use the predicted_label
and the model config to decode our prediction
. Here is what our predict
function looks like:
1 2 3 4 5 6 7 8 |
def predict(self, text): tokens = self.tokenizer.encode_plus(text, return_tensors='pt', padding=True, truncation=True) output = self.model(**tokens) logits = output.logits predicted_label = logits.argmax().item() self.Result.Text = "Result: " + self.model.config.id2label[predicted_label] |
Finally, we need a way to enable/disable our textbox and button based on which radio button is ticked. We will do this by first opening up Main.pyfmx
and creating an OnChange
event for both our TextboxRadio
and FilePickerRadio
buttons.
Next, let’s define our RadioChange
function. Open up Main.py
and create a new RadioChange
function. We define this function by checking if the TextboxRadio
button is checked. If checked, we enable the SentimentTextEdit
text box and disable the FilePickButton
. Otherwise, if the FilePickerRadio
button is checked, we simply turn off the SentimentTextEdit
text box and enable the FilePickButton
. Here is what our RadioChange
function looks like:
1 2 3 4 5 6 7 8 |
def RadioChange(self, Sender): if self.TextboxRadio.IsChecked: self.SentimentTextEdit.Enabled = True self.FilePickButton.Enabled = False if self.FilePickerRadio.IsChecked: self.SentimentTextEdit.Enabled = False self.FilePickButton.Enabled = True |
Here is what our final Main.py
file looks like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
import os from delphifmx import * # Additional imports from transformers import AutoTokenizer, AutoModelForSequenceClassification class MainForm(Form): def __init__(self, owner): self.Title = None self.Result = None self.FileName = None self.FilePickButton = None self.ResultButton = None self.OpenDialog1 = None self.SentimentTextEdit = None self.TextboxRadio = None self.FilePickerRadio = None self.Image1 = None self.StyleBook1 = None self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx")) # Initialize model and tokenizer self.tokenizer = AutoTokenizer.from_pretrained("ProsusAI/finbert") self.model = AutoModelForSequenceClassification.from_pretrained("ProsusAI/finbert") def FilePickButtonClick(self, Sender): self.OpenDialog1.Title = "Select an Image" # Filtering only image formats to show self.OpenDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*" if self.OpenDialog1.Execute(): self.FileName.Text = "Filename: " + os.path.basename(self.OpenDialog1.FileName) def ResultButtonClick(self, Sender): if self.TextboxRadio.IsChecked: text = self.SentimentTextEdit.Text print(text) self.predict(text) elif self.FilePickerRadio.IsChecked: with open(self.OpenDialog1.FileName, 'r') as file: text = file.read() print(text) self.predict(text) else: pass def predict(self, text): tokens = self.tokenizer.encode_plus(text, return_tensors='pt', padding=True, truncation=True) output = self.model(**tokens) logits = output.logits predicted_label = logits.argmax().item() self.Result.Text = "Result: " + self.model.config.id2label[predicted_label] def RadioChange(self, Sender): if self.TextboxRadio.IsChecked: self.SentimentTextEdit.Enabled = True self.FilePickButton.Enabled = False if self.FilePickerRadio.IsChecked: self.SentimentTextEdit.Enabled = False self.FilePickButton.Enabled = True |
Now that our application is ready, let’s test it out. Head over to Sentiment_Analysis_App.py
and run the file.
Now let’s test our application by selecting the Textbox radio button. This will enable the text box. Next, add some text to test out:
Finally, click on the Analyze Sentiment button to check out the result:
Similarly, we can test out the file picker by selecting the File Picker radio button. This enables the Select File button. Now press the button to open a dialog box and select a text file to analyze. For now, we will be using test.txt
. Here are the contents of our file: “The movie was an absolute disaster, with terrible acting, a nonsensical plot, and cringe-worthy dialogue. I wouldn’t recommend it to anyone.”
Once you’ve selected your text file, your file name should appear on the FileName
label:
Now click on the Analyze Sentiment button to check out the result:
What Are the Key Takeaways?
Congrats! We have successfully created a Sentiment Analysis app by leveraging Delphi’s powerful IDE, Delphifmx Python library, and incorporating a deep learning model from Hugging Face. This user-friendly application allows users to classify text as neutral, positive, or negative, empowering them to extract valuable insights from textual data. Delphi’s versatility, extensive features, and cross-platform capabilities make it an ideal choice for developers looking to build innovative applications.
What Are Some FAQs About this Topic?
What is Delphi?
Delphi is an IDE that allows developers to build applications using the Object Pascal programming language. It provides various tools and components for creating GUI-based applications across various platforms.
What is sentiment analysis?
Sentiment analysis determines a given text’s sentiment or emotional tone, such as a review, social media post, or customer feedback. It involves classifying the text as positive, negative, or neutral, providing insights into the writer’s opinion or attitude.
What is a deep learning model?
A deep learning model is a machine learning model that utilizes artificial neural networks with multiple layers to learn and extract complex patterns and representations from data. Deep learning models have been particularly successful in various domains, including NLP tasks like sentiment analysis.
What is Hugging Face?
Hugging Face is an open-source platform that provides a wide range of pre-trained models and tools for NLP. It offers resources such as transformer models, tokenizers, and libraries like Transformers, facilitating the development and deployment of NLP applications.
Can Delphi be used for building machine-learning applications?
Yes, Delphi can be used for building machine-learning applications. With its versatile IDE and frameworks like Delphi FMX, developers can create visually appealing and user-friendly GUIs for ML-powered applications. Additionally, tools like Delphi4PythonExporter enable integration with Python-based machine learning models, expanding the capabilities of Delphi in the ML domain.