cutechicken commited on
Commit
30e24b7
·
verified ·
1 Parent(s): 0bacf41

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +133 -0
app.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ import gradio as gr
4
+ import pandas as pd
5
+ import torch
6
+ from GoogleNews import GoogleNews
7
+ from transformers import pipeline
8
+
9
+ # Set up logging
10
+ logging.basicConfig(
11
+ level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
12
+ )
13
+
14
+ SENTIMENT_ANALYSIS_MODEL = (
15
+ "mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis"
16
+ )
17
+
18
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
19
+ logging.info(f"Using device: {DEVICE}")
20
+
21
+ logging.info("Initializing sentiment analysis model...")
22
+ sentiment_analyzer = pipeline(
23
+ "sentiment-analysis", model=SENTIMENT_ANALYSIS_MODEL, device=DEVICE
24
+ )
25
+ logging.info("Model initialized successfully")
26
+
27
+
28
+ def fetch_articles(query):
29
+ try:
30
+ logging.info(f"Fetching articles for query: '{query}'")
31
+ googlenews = GoogleNews(lang="en")
32
+ googlenews.search(query)
33
+ articles = googlenews.result()
34
+ logging.info(f"Fetched {len(articles)} articles")
35
+ return articles
36
+ except Exception as e:
37
+ logging.error(
38
+ f"Error while searching articles for query: '{query}'. Error: {e}"
39
+ )
40
+ raise gr.Error(
41
+ f"Unable to search articles for query: '{query}'. Try again later...",
42
+ duration=5,
43
+ )
44
+
45
+
46
+ def analyze_article_sentiment(article):
47
+ logging.info(f"Analyzing sentiment for article: {article['title']}")
48
+ sentiment = sentiment_analyzer(article["desc"])[0]
49
+ article["sentiment"] = sentiment
50
+ return article
51
+
52
+
53
+ def analyze_asset_sentiment(asset_name):
54
+ logging.info(f"Starting sentiment analysis for asset: {asset_name}")
55
+
56
+ logging.info("Fetching articles")
57
+ articles = fetch_articles(asset_name)
58
+
59
+ logging.info("Analyzing sentiment of each article")
60
+ analyzed_articles = [analyze_article_sentiment(article) for article in articles]
61
+
62
+ logging.info("Sentiment analysis completed")
63
+
64
+ return convert_to_dataframe(analyzed_articles)
65
+
66
+
67
+ def convert_to_dataframe(analyzed_articles):
68
+ df = pd.DataFrame(analyzed_articles)
69
+ df["Title"] = df.apply(
70
+ lambda row: f'<a href="{row["link"]}" target="_blank">{row["title"]}</a>',
71
+ axis=1,
72
+ )
73
+ df["Description"] = df["desc"]
74
+ df["Date"] = df["date"]
75
+
76
+ def sentiment_badge(sentiment):
77
+ colors = {
78
+ "negative": "red",
79
+ "neutral": "gray",
80
+ "positive": "green",
81
+ }
82
+ color = colors.get(sentiment, "grey")
83
+ return f'<span style="background-color: {color}; color: white; padding: 2px 6px; border-radius: 4px;">{sentiment}</span>'
84
+
85
+ df["Sentiment"] = df["sentiment"].apply(lambda x: sentiment_badge(x["label"]))
86
+ return df[["Sentiment", "Title", "Description", "Date"]]
87
+
88
+
89
+ with gr.Blocks() as iface:
90
+ gr.Markdown("# Trading Asset Sentiment Analysis")
91
+ gr.Markdown(
92
+ "Enter the name of a trading asset, and I'll fetch recent articles and analyze their sentiment!"
93
+ )
94
+
95
+ with gr.Row():
96
+ input_asset = gr.Textbox(
97
+ label="Asset Name",
98
+ lines=1,
99
+ placeholder="Enter the name of the trading asset...",
100
+ )
101
+
102
+ with gr.Row():
103
+ analyze_button = gr.Button("Analyze Sentiment", size="sm")
104
+
105
+ gr.Examples(
106
+ examples=[
107
+ "Bitcoin",
108
+ "Tesla",
109
+ "Apple",
110
+ "Amazon",
111
+ ],
112
+ inputs=input_asset,
113
+ )
114
+
115
+ with gr.Row():
116
+ with gr.Column():
117
+ with gr.Blocks():
118
+ gr.Markdown("## Articles and Sentiment Analysis")
119
+ articles_output = gr.Dataframe(
120
+ headers=["Sentiment", "Title", "Description", "Date"],
121
+ datatype=["markdown", "html", "markdown", "markdown"],
122
+ wrap=False,
123
+ )
124
+
125
+ analyze_button.click(
126
+ analyze_asset_sentiment,
127
+ inputs=[input_asset],
128
+ outputs=[articles_output],
129
+ )
130
+
131
+ logging.info("Launching Gradio interface")
132
+ iface.queue().launch()
133
+