Spaces:
Sleeping
Sleeping
File size: 10,283 Bytes
2ac4fcc |
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 |
import os
import gradio as gr
import pandas as pd
import torch
import logging
from transformers import pipeline, AutoModelForSequenceClassification, AutoTokenizer
import gc
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# Device configuration
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
logger.info(f"Using device: {DEVICE}")
def clear_gpu_memory():
"""Utility function to clear GPU memory"""
if DEVICE == "cuda":
torch.cuda.empty_cache()
gc.collect()
class ModelManager:
"""Handles model loading and inference"""
def __init__(self):
self.device = DEVICE
self.models = {}
self.tokenizers = {}
def load_model(self, model_name, model_type="sentiment"):
"""Load model and tokenizer"""
try:
if model_name not in self.models:
if model_type == "sentiment":
self.tokenizers[model_name] = AutoTokenizer.from_pretrained(model_name)
self.models[model_name] = AutoModelForSequenceClassification.from_pretrained(
model_name,
torch_dtype=torch.float16 if self.device == "cuda" else torch.float32
).to(self.device)
else:
self.models[model_name] = pipeline(
"text-generation",
model=model_name,
device_map="auto" if self.device == "cuda" else None,
torch_dtype=torch.float16 if self.device == "cuda" else torch.float32
)
logger.info(f"Loaded model: {model_name}")
except Exception as e:
logger.error(f"Error loading model {model_name}: {str(e)}")
raise
def unload_model(self, model_name):
"""Unload model and tokenizer"""
try:
if model_name in self.models:
del self.models[model_name]
if model_name in self.tokenizers:
del self.tokenizers[model_name]
clear_gpu_memory()
logger.info(f"Unloaded model: {model_name}")
except Exception as e:
logger.error(f"Error unloading model {model_name}: {str(e)}")
def get_model(self, model_name):
"""Get loaded model"""
return self.models.get(model_name)
def get_tokenizer(self, model_name):
"""Get loaded tokenizer"""
return self.tokenizers.get(model_name)
class FinancialAnalyzer:
"""Main analyzer class for financial statements"""
def __init__(self):
self.model_manager = ModelManager()
self.models = {
"sentiment": "ProsusAI/finbert",
"analysis": "TinyLlama/TinyLlama-1.1B-Chat-v1.0",
"recommendation": "tiiuae/falcon-rw-1b"
}
# Load sentiment model at initialization
try:
self.model_manager.load_model(self.models["sentiment"], "sentiment")
except Exception as e:
logger.error(f"Failed to initialize sentiment model: {str(e)}")
raise
def read_csv(self, file_obj):
"""Read and validate CSV file"""
try:
if file_obj is None:
raise ValueError("No file provided")
df = pd.read_csv(file_obj)
if df.empty:
raise ValueError("Empty CSV file")
return df.describe()
except Exception as e:
logger.error(f"Error reading CSV: {str(e)}")
raise
def analyze_sentiment(self, text):
"""Analyze sentiment using FinBERT"""
try:
model_name = self.models["sentiment"]
model = self.model_manager.get_model(model_name)
tokenizer = self.model_manager.get_tokenizer(model_name)
inputs = tokenizer(
text,
return_tensors="pt",
truncation=True,
max_length=512,
padding=True
).to(DEVICE)
with torch.no_grad():
outputs = model(**inputs)
probabilities = torch.nn.functional.softmax(outputs.logits, dim=1)
labels = ['negative', 'neutral', 'positive']
scores = probabilities[0].cpu().tolist()
results = [
{'label': label, 'score': score}
for label, score in zip(labels, scores)
]
return [results]
except Exception as e:
logger.error(f"Sentiment analysis error: {str(e)}")
return [{"label": "error", "score": 1.0}]
def generate_analysis(self, financial_data):
"""Generate strategic analysis"""
try:
model_name = self.models["analysis"]
self.model_manager.load_model(model_name, "generation")
prompt = f"""[INST] Analyze these financial statements:
{financial_data}
Provide:
1. Business Health Assessment
2. Key Strategic Insights
3. Market Position
4. Growth Opportunities
5. Risk Factors [/INST]"""
response = self.model_manager.get_model(model_name)(
prompt,
max_length=1000,
temperature=0.7,
do_sample=True,
num_return_sequences=1,
truncation=True
)
return response[0]['generated_text']
except Exception as e:
logger.error(f"Analysis generation error: {str(e)}")
return "Error in analysis generation"
finally:
self.model_manager.unload_model(model_name)
def generate_recommendations(self, analysis):
"""Generate recommendations"""
try:
model_name = self.models["recommendation"]
self.model_manager.load_model(model_name, "generation")
prompt = f"""Based on this analysis:
{analysis}
Provide actionable recommendations for:
1. Strategic Initiatives
2. Operational Improvements
3. Financial Management
4. Risk Mitigation
5. Growth Strategy"""
response = self.model_manager.get_model(model_name)(
prompt,
max_length=1000,
temperature=0.6,
do_sample=True,
num_return_sequences=1,
truncation=True
)
return response[0]['generated_text']
except Exception as e:
logger.error(f"Recommendations generation error: {str(e)}")
return "Error generating recommendations"
finally:
self.model_manager.unload_model(model_name)
def analyze_financial_statements(income_statement, balance_sheet):
"""Main analysis function"""
try:
analyzer = FinancialAnalyzer()
# Validate inputs
if not income_statement or not balance_sheet:
return "Error: Please provide both income statement and balance sheet files"
# Process financial statements
logger.info("Processing financial statements...")
income_summary = analyzer.read_csv(income_statement)
balance_summary = analyzer.read_csv(balance_sheet)
financial_data = f"""
Income Statement Summary:
{income_summary.to_string()}
Balance Sheet Summary:
{balance_summary.to_string()}
"""
# Generate analysis
logger.info("Generating analysis...")
analysis = analyzer.generate_analysis(financial_data)
# Analyze sentiment
logger.info("Analyzing sentiment...")
sentiment = analyzer.analyze_sentiment(analysis)
# Generate recommendations
logger.info("Generating recommendations...")
recommendations = analyzer.generate_recommendations(analysis)
# Format results
return format_results(analysis, sentiment, recommendations)
except Exception as e:
logger.error(f"Analysis error: {str(e)}")
return f"""Analysis Error:
{str(e)}
Please verify:
1. Files are valid CSV format
2. Files contain required financial data
3. File size is within limits"""
def format_results(analysis, sentiment, recommendations):
"""Format analysis results"""
try:
if not isinstance(analysis, str) or not isinstance(recommendations, str):
raise ValueError("Invalid input types")
output = [
"# Financial Analysis Report\n\n",
"## Strategic Analysis\n\n",
f"{analysis.strip()}\n\n",
"## Market Sentiment\n\n"
]
if isinstance(sentiment, list) and sentiment:
for score in sentiment[0]:
if isinstance(score, dict) and 'label' in score and 'score' in score:
output.append(f"- {score['label']}: {score['score']:.2%}\n")
output.append("\n")
output.append("## Strategic Recommendations\n\n")
output.append(f"{recommendations.strip()}")
return "".join(output)
except Exception as e:
logger.error(f"Formatting error: {str(e)}")
return "Error formatting results"
# Create Gradio interface
iface = gr.Interface(
fn=analyze_financial_statements,
inputs=[
gr.File(label="Income Statement (CSV)"),
gr.File(label="Balance Sheet (CSV)")
],
outputs=gr.Markdown(),
title="Financial Statement Analyzer",
description="""Upload financial statements for AI-powered analysis:
- Strategic Analysis (TinyLlama)
- Sentiment Analysis (FinBERT)
- Strategic Recommendations (Falcon)
Note: Please ensure files are in CSV format.""",
flagging_mode="never"
)
if __name__ == "__main__":
try:
iface.queue()
iface.launch(
share=False,
server_name="0.0.0.0",
server_port=7860
)
except Exception as e:
logger.error(f"Launch error: {str(e)}")
sys.exit(1)
|