shekolla commited on
Commit
781e0fa
1 Parent(s): b4331a8

Initial commit

Browse files
Files changed (3) hide show
  1. README.md +23 -0
  2. app.py +151 -0
  3. requirements.txt +2 -0
README.md CHANGED
@@ -11,3 +11,26 @@ license: mit
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
14
+
15
+
16
+ # Financial Sentiment Analysis with Huggingface Spaces
17
+
18
+ This project performs sentiment analysis on financial text using Huggingface Transformers and deploys the sentiment analysis model on Huggingface Spaces.
19
+
20
+ ## Overview
21
+
22
+ The Financial Sentiment Analysis project allows users to input financial text and receive sentiment analysis results, indicating whether the sentiment is positive, negative, or neutral. The sentiment analysis model is trained on financial news data and provides accurate predictions for financial sentiment classification.
23
+
24
+ ## Deployment on Huggingface Spaces
25
+
26
+ The project is deployed on Huggingface Spaces, allowing easy access and usage of the sentiment analysis model. To deploy the project on Spaces, follow the instructions below:
27
+
28
+ 1. Create a new space repository on Huggingface Spaces.
29
+
30
+ 2. Clone this repository to your local machine:
31
+ ```shell
32
+ git clone https://huggingface.co/spaces/shekolla/finbert-financial-sentiment
33
+
34
+ 3. Run the code:
35
+ ```bash
36
+ python app.py
app.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import pipeline
3
+
4
+
5
+ # Code Comment: Sentiment Analysis Model Selection
6
+
7
+ '''
8
+ When performing sentiment analysis on financial text, we have two model options to consider: `finBERT-tone` and `distilroberta-finetuned-financial-news-sentiment-analysis`.
9
+
10
+ - `finBERT-tone`: This model is specifically trained to identify seven tones (joy, fear, anger, sadness, analytical, confident, tentative) in financial text. It provides detailed insights into the emotional tone of the text, which can be valuable for sentiment analysis in specific contexts. It offers higher granularity, but it comes with a larger model size.
11
+
12
+ - `distilroberta-finetuned-financial-news-sentiment-analysis`: This model is based on DistilRoBERTa, a smaller and faster variant of RoBERTa. It is fine-tuned for sentiment analysis on financial news. This model strikes a good balance between model size and performance, offering a more compact option with lower resource requirements. Although it may not provide the same level of granularity as `finBERT-tone`, it still delivers reliable sentiment analysis results for financial text.
13
+
14
+ To ensure the best results, it is recommended to use `finBERT-tone` for sentiment analysis on financial text whenever possible. However, if size and resource constraints are a concern, or if a detailed emotional tone analysis is not required, you can fallback to `distilroberta-finetuned-financial-news-sentiment-analysis` as a reliable backup. It provides a smaller model size without sacrificing too much accuracy, making it a suitable alternative.
15
+
16
+ Keep in mind that both models have their strengths and trade-offs. Assess your specific requirements, available resources, and desired level of analysis to choose the most appropriate model for your sentiment analysis tasks.
17
+ '''
18
+
19
+ # End of Code Comment
20
+
21
+
22
+ def sentiment_analysis_generate_text(text):
23
+ # Define the model
24
+ model_name = "yiyanghkust/finbert-tone"
25
+
26
+ # for faster, less model size use this model
27
+ # model_name = "mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis"
28
+
29
+ # Create the pipeline
30
+ nlp = pipeline("sentiment-analysis", model=model_name)
31
+ # Split the input text into individual sentences
32
+ sentences = text.split('|')
33
+ # Run the pipeline on each sentence and collect the results
34
+ results = nlp(sentences)
35
+ output = []
36
+ for sentence, result in zip(sentences, results):
37
+ output.append(f"Text: {sentence.strip()}\nSentiment: {result['label']}, Score: {result['score']:.4f}\n")
38
+
39
+ # Join the results into a single string to return
40
+ return "\n".join(output)
41
+
42
+
43
+ def sentiment_analysis_generate_table(text):
44
+ # Define the model
45
+ model_name = "yiyanghkust/finbert-tone"
46
+ # Create the pipeline
47
+ nlp = pipeline("sentiment-analysis", model=model_name)
48
+ # Split the input text into individual sentences
49
+ sentences = text.split('|')
50
+
51
+ # Generate the HTML table with enhanced colors and bold headers
52
+ html = """
53
+ <html>
54
+ <head>
55
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/css/bootstrap.min.css">
56
+ <style>
57
+ .label {
58
+ transition: .15s;
59
+ border-radius: 8px;
60
+ padding: 5px 10px;
61
+ font-size: 14px;
62
+ text-transform: uppercase;
63
+ }
64
+ .positive {
65
+ background-color: rgb(54, 176, 75);
66
+ color: white;
67
+ }
68
+ .negative {
69
+ background-color: rgb(237, 83, 80);
70
+ color: white;
71
+ }
72
+ .neutral {
73
+ background-color: rgb(52, 152, 219);
74
+ color: white;
75
+ }
76
+ th {
77
+ font-weight: bold;
78
+ color: rgb(106, 38, 198);
79
+ }
80
+ </style>
81
+ </head>
82
+ <body>
83
+ <table class="table table-striped">
84
+ <thead>
85
+ <tr>
86
+ <th scope="col">Text</th>
87
+ <th scope="col">Score</th>
88
+ <th scope="col">Sentiment</th>
89
+ </tr>
90
+ </thead>
91
+ <tbody>
92
+ """
93
+ for sentence in sentences:
94
+ result = nlp(sentence.strip())[0]
95
+ text = sentence.strip()
96
+ score = f"{result['score']:.4f}"
97
+ sentiment = result['label']
98
+
99
+ # Determine the sentiment class
100
+ if sentiment == "Positive":
101
+ sentiment_class = "positive"
102
+ elif sentiment == "Negative":
103
+ sentiment_class = "negative"
104
+ else:
105
+ sentiment_class = "neutral"
106
+
107
+ # Generate table rows
108
+ html += f'<tr><td>{text}</td><td>{score}</td><td><span class="label {sentiment_class}">{sentiment}</span></td></tr>'
109
+
110
+ html += """
111
+ </tbody>
112
+ </table>
113
+ </body>
114
+ </html>
115
+ """
116
+
117
+ return html
118
+
119
+
120
+ if __name__ == "__main__":
121
+ # uncomment below code for using the code in text results
122
+ # iface = gr.Interface(
123
+ # fn=sentiment_analysis_generate_text,
124
+ # inputs="text",
125
+ # outputs="text",
126
+ # title="Financial Sentiment Analysis",
127
+ # description="<p>A sentiment analysis model fine-tuned on financial news.</p>"
128
+ # "<p>Enter some financial text to see whether the sentiment is positive, neutral or negative.</p>"
129
+ # "<p><strong>Note:</strong> Separate multiple sentences with a '|'.",
130
+ # )
131
+
132
+ # generate the result in html format
133
+ iface = gr.Interface(
134
+ sentiment_analysis_generate_table,
135
+ gr.Textbox(placeholder="Enter sentence here..."),
136
+ ["html"],
137
+ title="Financial Sentiment Analysis",
138
+ description="<p>A sentiment analysis model fine-tuned on financial news.</p>"
139
+ "<p>Enter some financial text to see whether the sentiment is positive, neutral or negative.</p>"
140
+ "<p><strong>Note:</strong> Separate multiple sentences with a '|'.",
141
+ examples=[
142
+ ['growth is strong and we have plenty of liquidity.'],
143
+ ['there is a shortage of capital, and we need extra financing.'],
144
+ ['formulation patents might protect Vasotec to a limited extent.'],
145
+ ["growth is strong and we have plenty of liquidity.|there is a shortage of capital"]
146
+ ],
147
+ allow_flagging=False,
148
+ examples_per_page=2,
149
+ )
150
+
151
+ iface.launch()
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ gradio==3.32.0
2
+ transformers==4.24.0