File size: 12,260 Bytes
c726c9b 49394d0 c726c9b |
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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 |
import gradio as gr
import json
import os
import torch
import nltk
import spacy
import re
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline, AutoModelForSeq2SeqLM
# Download necessary NLTK data for sentence tokenizations
try:
nltk.data.find('tokenizers/punkt')
except LookupError:
nltk.download('punkt')
SUMMARY_FILE = "training_summary.json"
# Assume label meanings are consistent with previous files
LABEL_MAP = {0: "Negative", 1: "Neutral", 2: "Positive"}
# Color coding for sentiment
COLOR_MAP = {
"Negative": "red",
"Neutral": "blue",
"Positive": "green"
}
# Global loading of models and NLP components
loaded_model = None
loaded_tokenizer = None
best_model_summary = None
summarizer = None
nlp = None # For NER
def load_models_and_components():
global loaded_model, loaded_tokenizer, best_model_summary, summarizer, nlp
# Load sentiment analysis model from training
if not os.path.exists(SUMMARY_FILE):
raise FileNotFoundError(f"Error: Could not find training summary file {SUMMARY_FILE}. Please run the fine-tuning and testing scripts first.")
with open(SUMMARY_FILE, 'r') as f:
summary_data = json.load(f)
if "best_model_details" not in summary_data or not summary_data["best_model_details"]:
raise ValueError(f"Error: Best model information not found or incomplete in {SUMMARY_FILE}.")
best_model_summary = summary_data["best_model_details"]
best_model_path = best_model_summary.get("best_model_path")
if not best_model_path:
best_model_path = summary_data.get("best_model_path") # Compatible with older format
if not best_model_path or not os.path.exists(best_model_path):
raise FileNotFoundError(f"Error: Best model path {best_model_path} not found or invalid.")
print(f"Loading sentiment model {best_model_summary['model_name']} from {best_model_path}...")
try:
loaded_tokenizer = AutoTokenizer.from_pretrained(best_model_path)
loaded_model = AutoModelForSequenceClassification.from_pretrained(best_model_path)
loaded_model.eval() # Set to evaluation mode
print("Sentiment model loaded successfully.")
except Exception as e:
raise RuntimeError(f"Failed to load sentiment model: {e}")
# Load summarization model
print("Loading summarization model...")
try:
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
print("Summarization model loaded successfully.")
except Exception as e:
print(f"Warning: Failed to load summarization model: {e}")
print("Will continue without summarization capability.")
summarizer = None
# Load spaCy model for NER (Named Entity Recognition)
print("Loading NER model...")
try:
# Download the model if it's not already downloaded
if not spacy.util.is_package("en_core_web_sm"):
spacy.cli.download("en_core_web_sm")
nlp = spacy.load("en_core_web_sm")
print("NER model loaded successfully.")
except Exception as e:
print(f"Warning: Failed to load NER model: {e}")
print("Will continue without NER capability.")
nlp = None
def predict_sentiment(text):
"""Predict sentiment for a single piece of text"""
global loaded_model, loaded_tokenizer
if not loaded_model or not loaded_tokenizer:
return "Error: Model not loaded.", None
if not text or not text.strip():
return "Please enter text for analysis.", None
try:
inputs = loaded_tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=128)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
loaded_model.to(device)
inputs = {k: v.to(device) for k, v in inputs.items()}
with torch.no_grad():
outputs = loaded_model(**inputs)
prediction_idx = torch.argmax(outputs.logits, dim=-1).item()
sentiment = LABEL_MAP.get(prediction_idx, f"Unknown ({prediction_idx})")
return sentiment, prediction_idx
except Exception as e:
print(f"Error during sentiment prediction: {e}")
return f"Error: {str(e)}", None
def generate_summary(text):
"""Generate a summary for longer text"""
global summarizer
if not summarizer:
return "Summarization model not available."
if not text or len(text.strip()) < 50:
return "Text too short for summarization."
try:
# BART has a max length, so we'll truncate if needed
max_length = min(1024, len(text.split()))
summary = summarizer(text, max_length=max_length//4, min_length=30, do_sample=False)
return summary[0]['summary_text']
except Exception as e:
print(f"Error during summarization: {e}")
return f"Summarization error: {str(e)}"
def identify_entities(text):
"""Identify locations and organizations in the text"""
global nlp
if not nlp:
return "NER model not available."
if not text or not text.strip():
return "Please enter text for entity analysis."
try:
doc = nlp(text)
locations = []
organizations = []
for ent in doc.ents:
if ent.label_ == "GPE" or ent.label_ == "LOC": # Geopolitical entity or Location
locations.append(ent.text)
elif ent.label_ == "ORG": # Organization
organizations.append(ent.text)
# Remove duplicates and sort
locations = sorted(list(set(locations)))
organizations = sorted(list(set(organizations)))
return {
"locations": locations,
"organizations": organizations
}
except Exception as e:
print(f"Error during entity identification: {e}")
return f"Entity identification error: {str(e)}"
def format_entities(entities):
"""Format identified entities for display"""
if isinstance(entities, str): # Error message
return entities
formatted = "<h3>Interested Parties</h3>"
# Add locations in red
if entities["locations"]:
formatted += "<p><b>Locations:</b> "
formatted += ", ".join([f"<span style='color: red'>{loc}</span>" for loc in entities["locations"]])
formatted += "</p>"
else:
formatted += "<p><b>Locations:</b> None identified</p>"
# Add organizations in green
if entities["organizations"]:
formatted += "<p><b>Organizations:</b> "
formatted += ", ".join([f"<span style='color: green'>{org}</span>" for org in entities["organizations"]])
formatted += "</p>"
else:
formatted += "<p><b>Organizations:</b> None identified</p>"
return formatted
def analyze_text_sentiment_by_sentence(text):
"""Analyze sentiment of each sentence in the text and format with colors"""
if not text or not text.strip():
return "Please enter text for analysis."
try:
# Split text into sentences
sentences = nltk.sent_tokenize(text)
formatted_result = ""
for sentence in sentences:
if len(sentence.strip()) < 3: # Skip very short sentences
continue
sentiment, _ = predict_sentiment(sentence)
color = COLOR_MAP.get(sentiment, "black")
formatted_result += f"<span style='color: {color}'>{sentence}</span> "
return formatted_result if formatted_result else "No valid sentences found for analysis."
except Exception as e:
print(f"Error during sentence-level sentiment analysis: {e}")
return f"Error: {str(e)}"
def analyze_financial_text(text):
"""Master function that performs all analysis tasks"""
if not text or not text.strip():
return "Please enter text for analysis.", "No summary available.", "No entities identified."
# Generate summary
summary = generate_summary(text)
# Perform sentence-level sentiment analysis
sentiment_analysis = analyze_text_sentiment_by_sentence(text)
# Identify entities
entities = identify_entities(text)
formatted_entities = format_entities(entities)
return sentiment_analysis, summary, formatted_entities
# Try to load models at app startup
try:
load_models_and_components()
except Exception as e:
print(f"Initial model loading failed: {e}")
# Gradio interface will still start, but functionality will be limited
# Build Gradio interface
model_info = "### Model Information\n"
if best_model_summary:
model_name = best_model_summary.get("model_name", "N/A")
accuracy = best_model_summary.get("accuracy_percent", "N/A")
run_time = best_model_summary.get("run_time_sec", "N/A")
hyperparams = best_model_summary.get("hyperparameters", {})
model_info += f"- **Model Name**: {model_name}\n"
model_info += f"- **Model Accuracy**: {accuracy}%\n"
model_info += f"- **Description**: The model is trained and fine-tuned using the financial news dataset to improve its sensitivity in recognizing financial sentiment.\n"
# Add hyperparameters
model_info += "\n### Hyperparameters\n"
model_info += f"- **Learning Rate**: {hyperparams.get('learning_rate', 'N/A')}\n"
model_info += f"- **Batch Size**: {hyperparams.get('batch_size', 'N/A')}\n"
model_info += f"- **Number of Epochs**: {hyperparams.get('num_epochs', 'N/A')}\n"
else:
model_info += "Model information loading failed. Please check the `training_summary.json` file and backend logs."
# Gradio interface definition
app_title = "ISOM5240_financial_tone"
app_description = (
"Analyze financial news text to extract summary, sentiment, and identify interested parties. "
"The sentiment analysis model is fine-tuned on financial news data."
)
with gr.Blocks(title=app_title) as iface:
gr.Markdown(f"# {app_title}")
gr.Markdown(app_description)
with gr.Row():
with gr.Column(scale=2):
input_text = gr.Textbox(
lines=10,
label="Financial News Text",
placeholder="Enter a longer financial news text here for analysis..."
)
analyze_btn = gr.Button("Start Analysis", variant="primary")
with gr.Column(scale=1):
gr.Markdown(model_info)
with gr.Row():
with gr.Column():
gr.Markdown("### Text Summary")
summary_output = gr.Textbox(label="Summary", lines=3)
with gr.Row():
with gr.Column():
gr.Markdown("### Sentiment Analysis (Sentence-level)")
gr.Markdown("- <span style='color: green'>Green</span>: Positive")
gr.Markdown("- <span style='color: blue'>Blue</span>: Neutral")
gr.Markdown("- <span style='color: red'>Red</span>: Negative")
sentiment_output = gr.HTML(label="Sentiment")
with gr.Row():
with gr.Column():
entities_output = gr.HTML(label="Interested Parties")
# Set up the click event for the analyze button
analyze_btn.click(
fn=analyze_financial_text,
inputs=[input_text],
outputs=[sentiment_output, summary_output, entities_output]
)
# Add examples
gr.Examples(
[
["The Federal Reserve announced today that interest rates will remain unchanged. Markets responded positively, with the S&P 500 gaining 1.2%. However, smaller tech companies in Silicon Valley expressed concerns about potential future rate hikes affecting their access to capital."],
["Apple Inc. reported record quarterly revenue of $91.8 billion, an increase of 9% from the year-ago quarter. The company's CEO Tim Cook attributed this success to strong international sales, particularly in European markets and China. However, supply chain disruptions in Taiwan may impact future quarters."]
],
inputs=input_text
)
if __name__ == "__main__":
print("Starting Gradio application...")
# share=True will generate a public link
iface.launch(share=True) |