Spaces:
Runtime error
Runtime error
| import logging | |
| import gradio as gr | |
| import pandas as pd | |
| import torch | |
| from GoogleNews import GoogleNews | |
| from transformers import pipeline | |
| # Set up logging | |
| logging.basicConfig( | |
| level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" | |
| ) | |
| SENTIMENT_ANALYSIS_MODEL = ( | |
| "mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis" | |
| ) | |
| DEVICE = "cuda" if torch.cuda.is_available() else "cpu" | |
| logging.info(f"Using device: {DEVICE}") | |
| logging.info("Initializing sentiment analysis model...") | |
| sentiment_analyzer = pipeline( | |
| "sentiment-analysis", model=SENTIMENT_ANALYSIS_MODEL, device=DEVICE | |
| ) | |
| logging.info("Model initialized successfully") | |
| def fetch_articles(query, max_articles=30): | |
| try: | |
| logging.info(f"Fetching up to {max_articles} articles for query: '{query}'") | |
| googlenews = GoogleNews(lang="en") | |
| googlenews.search(query) | |
| # ์ฒซ ํ์ด์ง ๊ฒฐ๊ณผ ๊ฐ์ ธ์ค๊ธฐ | |
| articles = googlenews.result() | |
| # ๋ชฉํ ๊ธฐ์ฌ ์์ ๋๋ฌํ ๋๊น์ง ์ถ๊ฐ ํ์ด์ง ๊ฐ์ ธ์ค๊ธฐ | |
| page = 2 | |
| while len(articles) < max_articles and page <= 10: # ์ต๋ 10ํ์ด์ง๊น์ง๋ง ์๋ | |
| logging.info(f"Fetched {len(articles)} articles so far. Getting page {page}...") | |
| googlenews.get_page(page) | |
| page_results = googlenews.result() | |
| # ์ ๊ฒฐ๊ณผ๊ฐ ์์ผ๋ฉด ์ค๋จ | |
| if not page_results: | |
| logging.info(f"No more results found after page {page-1}") | |
| break | |
| articles.extend(page_results) | |
| page += 1 | |
| # ์ต๋ ๊ธฐ์ฌ ์๋ก ์ ํ | |
| articles = articles[:max_articles] | |
| logging.info(f"Successfully fetched {len(articles)} articles") | |
| return articles | |
| except Exception as e: | |
| logging.error( | |
| f"Error while searching articles for query: '{query}'. Error: {e}" | |
| ) | |
| raise gr.Error( | |
| f"Unable to search articles for query: '{query}'. Try again later...", | |
| duration=5, | |
| ) | |
| def analyze_article_sentiment(article): | |
| logging.info(f"Analyzing sentiment for article: {article['title']}") | |
| sentiment = sentiment_analyzer(article["desc"])[0] | |
| article["sentiment"] = sentiment | |
| return article | |
| def analyze_asset_sentiment(asset_name): | |
| logging.info(f"Starting sentiment analysis for asset: {asset_name}") | |
| logging.info("Fetching up to 30 articles") | |
| articles = fetch_articles(asset_name, max_articles=30) | |
| logging.info("Analyzing sentiment of each article") | |
| analyzed_articles = [analyze_article_sentiment(article) for article in articles] | |
| logging.info("Sentiment analysis completed") | |
| return convert_to_dataframe(analyzed_articles) | |
| def convert_to_dataframe(analyzed_articles): | |
| df = pd.DataFrame(analyzed_articles) | |
| df["Title"] = df.apply( | |
| lambda row: f'<a href="{row["link"]}" target="_blank">{row["title"]}</a>', | |
| axis=1, | |
| ) | |
| df["Description"] = df["desc"] | |
| df["Date"] = df["date"] | |
| def sentiment_badge(sentiment): | |
| colors = { | |
| "negative": "red", | |
| "neutral": "gray", | |
| "positive": "green", | |
| } | |
| color = colors.get(sentiment, "grey") | |
| return f'<span style="background-color: {color}; color: white; padding: 2px 6px; border-radius: 4px;">{sentiment}</span>' | |
| df["Sentiment"] = df["sentiment"].apply(lambda x: sentiment_badge(x["label"])) | |
| return df[["Sentiment", "Title", "Description", "Date"]] | |
| with gr.Blocks() as iface: | |
| gr.Markdown("# Trading Asset Sentiment Analysis") | |
| gr.Markdown( | |
| "Enter the name of a trading asset, and I'll fetch recent articles and analyze their sentiment!" | |
| ) | |
| with gr.Row(): | |
| input_asset = gr.Textbox( | |
| label="Asset Name", | |
| lines=1, | |
| placeholder="Enter the name of the trading asset...", | |
| ) | |
| with gr.Row(): | |
| analyze_button = gr.Button("Analyze Sentiment", size="sm") | |
| gr.Examples( | |
| examples=[ | |
| "Bitcoin", | |
| "Tesla", | |
| "Apple", | |
| "Amazon", | |
| ], | |
| inputs=input_asset, | |
| ) | |
| with gr.Row(): | |
| with gr.Column(): | |
| with gr.Blocks(): | |
| gr.Markdown("## Articles and Sentiment Analysis") | |
| articles_output = gr.Dataframe( | |
| headers=["Sentiment", "Title", "Description", "Date"], | |
| datatype=["markdown", "html", "markdown", "markdown"], | |
| wrap=False, | |
| ) | |
| analyze_button.click( | |
| analyze_asset_sentiment, | |
| inputs=[input_asset], | |
| outputs=[articles_output], | |
| ) | |
| logging.info("Launching Gradio interface") | |
| iface.queue().launch() |