Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,129 +1,164 @@
|
|
1 |
import gradio as gr
|
2 |
import pandas as pd
|
3 |
-
from transformers import pipeline
|
4 |
import torch
|
5 |
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
model="meta-llama/Llama-2-7b-chat-hf",
|
13 |
-
device_map="auto"
|
14 |
-
)
|
15 |
-
|
16 |
-
# 2. FinBERT for financial sentiment
|
17 |
-
self.financial_analyzer = pipeline(
|
18 |
"text-classification",
|
19 |
model="ProsusAI/finbert",
|
20 |
return_all_scores=True
|
21 |
)
|
|
|
22 |
|
23 |
-
#
|
24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
"text-generation",
|
26 |
-
model="tiiuae/falcon-7b
|
|
|
27 |
device_map="auto"
|
28 |
)
|
29 |
-
|
30 |
-
def generate_strategic_analysis(self, financial_data):
|
31 |
-
"""Generate strategic analysis using Llama 2"""
|
32 |
-
prompt = f"""[INST] As a senior financial analyst, analyze these financial statements:
|
33 |
-
|
34 |
-
Financial Data:
|
35 |
-
{financial_data}
|
36 |
-
|
37 |
-
Provide:
|
38 |
-
1. Business Health Assessment
|
39 |
-
2. Key Strategic Insights
|
40 |
-
3. Market Position Analysis
|
41 |
-
4. Growth Opportunities
|
42 |
-
5. Risk Factors [/INST]"""
|
43 |
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
)
|
49 |
-
return response[0]['generated_text']
|
50 |
-
|
51 |
-
def analyze_sentiment(self, text):
|
52 |
-
"""Analyze financial sentiment using FinBERT"""
|
53 |
-
return self.financial_analyzer(text)
|
54 |
-
|
55 |
-
def generate_recommendations(self, analysis):
|
56 |
-
"""Generate recommendations using Falcon"""
|
57 |
-
prompt = f"""Based on this financial analysis:
|
58 |
-
{analysis}
|
59 |
-
|
60 |
-
Provide specific, actionable recommendations covering:
|
61 |
-
1. Strategic Initiatives
|
62 |
-
2. Operational Improvements
|
63 |
-
3. Financial Management
|
64 |
-
4. Risk Mitigation
|
65 |
-
5. Growth Strategy"""
|
66 |
-
|
67 |
-
response = self.recommendation_generator(
|
68 |
-
prompt,
|
69 |
-
max_length=800,
|
70 |
-
temperature=0.6
|
71 |
-
)
|
72 |
-
return response[0]['generated_text']
|
73 |
|
74 |
def analyze_financial_statements(income_statement, balance_sheet):
|
75 |
-
"""
|
76 |
try:
|
77 |
-
#
|
78 |
income_df = pd.read_csv(income_statement.name)
|
79 |
balance_df = pd.read_csv(balance_sheet.name)
|
80 |
|
81 |
-
#
|
82 |
-
|
83 |
-
|
84 |
-
# Prepare financial data
|
85 |
-
financial_data = f"""
|
86 |
-
Income Statement Summary:
|
87 |
-
{income_df.to_string()}
|
88 |
-
|
89 |
-
Balance Sheet Summary:
|
90 |
-
{balance_df.to_string()}
|
91 |
-
"""
|
92 |
-
|
93 |
-
# Generate strategic analysis
|
94 |
-
strategic_analysis = analyzer.generate_strategic_analysis(financial_data)
|
95 |
|
96 |
-
#
|
97 |
-
|
|
|
|
|
98 |
|
99 |
-
# Generate
|
100 |
-
|
101 |
|
102 |
-
# Format
|
103 |
-
|
104 |
-
|
105 |
-
return output
|
106 |
|
107 |
except Exception as e:
|
108 |
return f"Error analyzing files: {str(e)}"
|
109 |
|
110 |
-
def
|
111 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
112 |
output = "# Financial Analysis Report\n\n"
|
113 |
|
114 |
# Strategic Analysis
|
115 |
output += "## Strategic Analysis\n\n"
|
116 |
-
output += analysis + "\n\n"
|
117 |
|
118 |
-
# Sentiment
|
119 |
output += "## Market Sentiment\n\n"
|
120 |
-
for score in sentiment[0]:
|
121 |
output += f"- {score['label']}: {score['score']:.2%}\n"
|
122 |
output += "\n"
|
123 |
|
124 |
# Recommendations
|
125 |
output += "## Strategic Recommendations\n\n"
|
126 |
-
output += recommendations
|
127 |
|
128 |
return output
|
129 |
|
@@ -137,9 +172,11 @@ iface = gr.Interface(
|
|
137 |
outputs=gr.Markdown(),
|
138 |
title="AI-Powered Financial Statement Analysis",
|
139 |
description="""Upload your financial statements for comprehensive analysis using:
|
140 |
-
- Llama 2: Strategic Analysis
|
141 |
- FinBERT: Financial Sentiment Analysis
|
142 |
-
- Falcon: Strategic Recommendations
|
|
|
|
|
143 |
examples=[
|
144 |
[
|
145 |
"OFINTECH-Income Statement-template.csv",
|
|
|
1 |
import gradio as gr
|
2 |
import pandas as pd
|
3 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
4 |
import torch
|
5 |
|
6 |
+
def load_models():
|
7 |
+
"""Initialize models with proper error handling"""
|
8 |
+
models = {}
|
9 |
+
try:
|
10 |
+
# 1. Load FinBERT (always works, no approval needed)
|
11 |
+
models['finbert'] = pipeline(
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
"text-classification",
|
13 |
model="ProsusAI/finbert",
|
14 |
return_all_scores=True
|
15 |
)
|
16 |
+
print("✓ FinBERT loaded successfully")
|
17 |
|
18 |
+
# 2. Try loading Llama 2 (requires approval)
|
19 |
+
try:
|
20 |
+
models['llama2'] = pipeline(
|
21 |
+
"text-generation",
|
22 |
+
model="meta-llama/Llama-2-7b-chat-hf",
|
23 |
+
torch_dtype=torch.float16,
|
24 |
+
device_map="auto"
|
25 |
+
)
|
26 |
+
print("✓ Llama 2 loaded successfully")
|
27 |
+
except Exception as e:
|
28 |
+
print(f"⚠️ Llama 2 not available: {str(e)}")
|
29 |
+
# Fallback to Falcon
|
30 |
+
models['llama2'] = pipeline(
|
31 |
+
"text-generation",
|
32 |
+
model="tiiuae/falcon-7b",
|
33 |
+
torch_dtype=torch.float16,
|
34 |
+
device_map="auto"
|
35 |
+
)
|
36 |
+
print("✓ Using Falcon as fallback for analysis")
|
37 |
+
|
38 |
+
# 3. Load Falcon (always works, no approval needed)
|
39 |
+
models['falcon'] = pipeline(
|
40 |
"text-generation",
|
41 |
+
model="tiiuae/falcon-7b",
|
42 |
+
torch_dtype=torch.float16,
|
43 |
device_map="auto"
|
44 |
)
|
45 |
+
print("✓ Falcon loaded successfully")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
46 |
|
47 |
+
return models
|
48 |
+
except Exception as e:
|
49 |
+
print(f"Error loading models: {str(e)}")
|
50 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
|
52 |
def analyze_financial_statements(income_statement, balance_sheet):
|
53 |
+
"""Analyze financial statements using AI models"""
|
54 |
try:
|
55 |
+
# Load data
|
56 |
income_df = pd.read_csv(income_statement.name)
|
57 |
balance_df = pd.read_csv(balance_sheet.name)
|
58 |
|
59 |
+
# Prepare financial data summary
|
60 |
+
financial_data = prepare_financial_summary(income_df, balance_df)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
|
62 |
+
# Load models
|
63 |
+
models = load_models()
|
64 |
+
if not models:
|
65 |
+
return "Error: Could not load analysis models."
|
66 |
|
67 |
+
# Generate analyses
|
68 |
+
analysis = generate_analysis(models, financial_data)
|
69 |
|
70 |
+
# Format and return results
|
71 |
+
return format_results(analysis)
|
|
|
|
|
72 |
|
73 |
except Exception as e:
|
74 |
return f"Error analyzing files: {str(e)}"
|
75 |
|
76 |
+
def prepare_financial_summary(income_df, balance_df):
|
77 |
+
"""Prepare financial data summary"""
|
78 |
+
latest_year = income_df['Period'].iloc[-1]
|
79 |
+
previous_year = income_df['Period'].iloc[-2]
|
80 |
+
|
81 |
+
summary = f"""Financial Analysis for {latest_year}:
|
82 |
+
|
83 |
+
Income Statement Summary:
|
84 |
+
- Revenue: {income_df['Revenue'].iloc[-1]}
|
85 |
+
- Gross Profit: {income_df['Gross Profit'].iloc[-1]}
|
86 |
+
- Net Income: {income_df['Net Income'].iloc[-1]}
|
87 |
+
- YoY Revenue Growth: {(income_df['Revenue'].iloc[-1] / income_df['Revenue'].iloc[-2] - 1) * 100:.1f}%
|
88 |
+
- YoY Net Income Growth: {(income_df['Net Income'].iloc[-1] / income_df['Net Income'].iloc[-2] - 1) * 100:.1f}%
|
89 |
+
|
90 |
+
Balance Sheet Summary:
|
91 |
+
- Total Assets: {balance_df['Total Assets'].iloc[-1]}
|
92 |
+
- Total Liabilities: {balance_df['Total Liabilities'].iloc[-1]}
|
93 |
+
- Shareholder's Equity: {balance_df["Shareholder's Equity"].iloc[-1]}
|
94 |
+
- Current Ratio: {balance_df['Total current assets'].iloc[-1] / balance_df['Total current liabilities'].iloc[-1]:.2f}"""
|
95 |
+
|
96 |
+
return summary
|
97 |
+
|
98 |
+
def generate_analysis(models, financial_data):
|
99 |
+
"""Generate comprehensive analysis using all models"""
|
100 |
+
|
101 |
+
# 1. Strategic Analysis (Llama 2 or Falcon)
|
102 |
+
strategy_prompt = f"""[INST] As a senior financial analyst, analyze these financial metrics and provide strategic insights:
|
103 |
+
|
104 |
+
{financial_data}
|
105 |
+
|
106 |
+
Provide analysis covering:
|
107 |
+
1. Financial Health Assessment
|
108 |
+
2. Key Performance Indicators
|
109 |
+
3. Growth Analysis
|
110 |
+
4. Risk Factors
|
111 |
+
5. Strategic Position [/INST]"""
|
112 |
+
|
113 |
+
strategic_analysis = models['llama2'](
|
114 |
+
strategy_prompt,
|
115 |
+
max_length=1000,
|
116 |
+
temperature=0.7
|
117 |
+
)[0]['generated_text']
|
118 |
+
|
119 |
+
# 2. Financial Sentiment (FinBERT)
|
120 |
+
sentiment = models['finbert'](strategic_analysis)
|
121 |
+
|
122 |
+
# 3. Recommendations (Falcon)
|
123 |
+
recommendations_prompt = f"""Based on this financial analysis:
|
124 |
+
{strategic_analysis}
|
125 |
+
|
126 |
+
Provide specific, actionable recommendations for:
|
127 |
+
1. Immediate Actions (0-6 months)
|
128 |
+
2. Short-term Strategy (6-12 months)
|
129 |
+
3. Medium-term Initiatives (1-2 years)
|
130 |
+
4. Risk Mitigation
|
131 |
+
5. Growth Opportunities"""
|
132 |
+
|
133 |
+
recommendations = models['falcon'](
|
134 |
+
recommendations_prompt,
|
135 |
+
max_length=800,
|
136 |
+
temperature=0.6
|
137 |
+
)[0]['generated_text']
|
138 |
+
|
139 |
+
return {
|
140 |
+
'strategic_analysis': strategic_analysis,
|
141 |
+
'sentiment': sentiment,
|
142 |
+
'recommendations': recommendations
|
143 |
+
}
|
144 |
+
|
145 |
+
def format_results(analysis):
|
146 |
+
"""Format analysis results into readable report"""
|
147 |
output = "# Financial Analysis Report\n\n"
|
148 |
|
149 |
# Strategic Analysis
|
150 |
output += "## Strategic Analysis\n\n"
|
151 |
+
output += analysis['strategic_analysis'].split('[/INST]')[-1].strip() + "\n\n"
|
152 |
|
153 |
+
# Market Sentiment
|
154 |
output += "## Market Sentiment\n\n"
|
155 |
+
for score in analysis['sentiment'][0]:
|
156 |
output += f"- {score['label']}: {score['score']:.2%}\n"
|
157 |
output += "\n"
|
158 |
|
159 |
# Recommendations
|
160 |
output += "## Strategic Recommendations\n\n"
|
161 |
+
output += analysis['recommendations']
|
162 |
|
163 |
return output
|
164 |
|
|
|
172 |
outputs=gr.Markdown(),
|
173 |
title="AI-Powered Financial Statement Analysis",
|
174 |
description="""Upload your financial statements for comprehensive analysis using:
|
175 |
+
- Llama 2 / Falcon: Strategic Analysis
|
176 |
- FinBERT: Financial Sentiment Analysis
|
177 |
+
- Falcon: Strategic Recommendations
|
178 |
+
|
179 |
+
Note: The system will automatically use available models based on access permissions.""",
|
180 |
examples=[
|
181 |
[
|
182 |
"OFINTECH-Income Statement-template.csv",
|