su commited on
Commit
9ef92ae
1 Parent(s): faf8aca

requirements and app file

Browse files
Files changed (2) hide show
  1. app.py +120 -0
  2. requirements.txt +7 -0
app.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import os
4
+ import json
5
+ from transformers import pipeline
6
+ import matplotlib.pyplot as plt
7
+ import numpy as np
8
+ import pandas as pd
9
+
10
+
11
+
12
+
13
+ bearer_token = os.environ.get("BEARER_TOKEN")
14
+ print(bearer_token)
15
+
16
+
17
+ search_url = "https://api.twitter.com/2/tweets/search/recent"
18
+
19
+
20
+
21
+ def bearer_oauth(r):
22
+ """
23
+ Method required by bearer token authentication.
24
+ """
25
+
26
+ r.headers["Authorization"] = f"Bearer {bearer_token}"
27
+ r.headers["User-Agent"] = "v2RecentSearchPython"
28
+ return r
29
+
30
+ def connect_to_endpoint(url, params):
31
+ response = requests.get(url, auth=bearer_oauth, params=params)
32
+ print(response.status_code)
33
+ if response.status_code != 200:
34
+ raise Exception(response.status_code, response.text)
35
+ return response.json()
36
+
37
+
38
+ def fetch_tweets(tag):
39
+ q = "\"" + tag + "\""
40
+ query_params = {'query': q, 'tweet.fields': 'author_id', 'max_results': 100}
41
+ json_response = connect_to_endpoint(search_url, query_params)
42
+ #print(json.dumps(json_response, indent=4, sort_keys=True))
43
+ phrases = []
44
+ for entry in json_response["data"]:
45
+ phrases.append(entry["text"])
46
+ return phrases
47
+
48
+ pipe = pipeline("text-classification", model="mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis")
49
+
50
+ def analyze_phrases(phrases):
51
+ positive = 0
52
+ positive_examples = {}
53
+ negative = 0
54
+ negative_examples = {}
55
+ neutral = 0
56
+ neutral_examples = {}
57
+ outputs = pipe(phrases)
58
+ for index, x in enumerate(outputs):
59
+ if x['label'] == 'positive':
60
+ positive += 1
61
+ if positive <= 3:
62
+ positive_examples[phrases[index]] = x['score']
63
+ elif x['label'] == 'neutral':
64
+ neutral += 1
65
+ if neutral <= 3:
66
+ neutral_examples[phrases[index]] = x['score']
67
+ elif x['label'] == 'negative':
68
+ negative += 1
69
+ if negative <= 3:
70
+ negative_examples[phrases[index]] = x['score']
71
+ else:
72
+ pass
73
+ counts = [positive, neutral, negative]
74
+ return counts, positive_examples, neutral_examples, negative_examples
75
+
76
+
77
+ def calculate_sentiment(tag):
78
+ phrases = fetch_tweets(tag)
79
+ counts, positive_examples, neutral_examples, negative_examples = analyze_phrases(phrases)
80
+ output = "positive: " + str(counts[0]) + "\n" + "neutral: " + str(counts[1]) + "\n" + "negative: " + str(counts[2])
81
+ plt.style.use('_mpl-gallery-nogrid')
82
+
83
+
84
+ # make data
85
+ colors = ['green', 'yellow', 'red']
86
+ labels = ["Positive", "Neutral", "Negative"]
87
+
88
+ # plot
89
+ fig, ax = plt.subplots(figsize=(10, 6))
90
+ wedges, texts = ax.pie(counts, colors=colors, radius=3, center=(4, 4),
91
+ wedgeprops={"linewidth": 1, "edgecolor": "white"}, labeldistance=1.05)
92
+
93
+ # Create a legend
94
+ ax.legend(wedges, labels, title="Categories", loc="center left", bbox_to_anchor=(1, 0, 0.5, 1))
95
+
96
+ ax.set(xlim=(0, 8),
97
+ ylim=(0, 8))
98
+ print(positive_examples)
99
+ html_content = ""
100
+ positive_tweets = list(positive_examples.items())
101
+ p_df = pd.DataFrame(positive_tweets, columns=["Tweet", "Confidence"])
102
+ positive_table = p_df.to_html(index=False)
103
+
104
+ neutral_tweets = list(neutral_examples.items())
105
+ n_df = pd.DataFrame(neutral_tweets, columns=["Tweet", "Confidence"])
106
+ neutral_table = n_df.to_html(index=False)
107
+
108
+ negative_tweets = list(negative_examples.items())
109
+ neg_df = pd.DataFrame(negative_tweets, columns=["Tweet", "Confidence"])
110
+ negative_table = neg_df.to_html(index=False)
111
+
112
+ html_content += f"<h2>Recent Positive Tweets</h2>" + positive_table
113
+ html_content += f"<h2>Recent Negative Tweets</h2>" + negative_table
114
+
115
+
116
+ return fig, html_content
117
+
118
+
119
+ iface = gr.Interface(fn=calculate_sentiment, inputs="text", outputs=["plot","html"])
120
+ iface.launch(debug=True)
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ requests
2
+ os
3
+ json
4
+ transformers
5
+ matplotlib
6
+ numpy
7
+ pandas