Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,164 +1,166 @@
|
|
1 |
import gradio as gr
|
2 |
import pandas as pd
|
3 |
-
from transformers import
|
4 |
import torch
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
"text-classification",
|
13 |
model="ProsusAI/finbert",
|
14 |
return_all_scores=True
|
15 |
)
|
16 |
-
print("✓ FinBERT loaded successfully")
|
17 |
|
18 |
-
#
|
19 |
-
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
46 |
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
|
52 |
-
def analyze_financial_statements(income_statement, balance_sheet):
|
53 |
-
"""
|
54 |
try:
|
55 |
-
#
|
56 |
income_df = pd.read_csv(income_statement.name)
|
57 |
balance_df = pd.read_csv(balance_sheet.name)
|
58 |
|
59 |
-
#
|
60 |
-
|
61 |
|
62 |
-
#
|
63 |
-
|
64 |
-
if
|
65 |
-
|
66 |
|
67 |
-
#
|
68 |
-
|
|
|
|
|
69 |
|
70 |
-
|
71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
72 |
|
73 |
except Exception as e:
|
74 |
return f"Error analyzing files: {str(e)}"
|
75 |
|
76 |
-
def
|
77 |
-
"""
|
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
|
|
|
|
|
|
|
|
|
|
|
152 |
|
153 |
-
#
|
154 |
output += "## Market Sentiment\n\n"
|
155 |
-
for score in
|
156 |
output += f"- {score['label']}: {score['score']:.2%}\n"
|
157 |
output += "\n"
|
158 |
|
159 |
# Recommendations
|
160 |
output += "## Strategic Recommendations\n\n"
|
161 |
-
output +=
|
162 |
|
163 |
return output
|
164 |
|
@@ -167,20 +169,25 @@ iface = gr.Interface(
|
|
167 |
fn=analyze_financial_statements,
|
168 |
inputs=[
|
169 |
gr.File(label="Income Statement (CSV)"),
|
170 |
-
gr.File(label="Balance Sheet (CSV)")
|
|
|
171 |
],
|
172 |
outputs=gr.Markdown(),
|
173 |
title="AI-Powered Financial Statement Analysis",
|
174 |
-
description="""Upload your financial statements for comprehensive analysis using:
|
175 |
-
- Llama 2
|
176 |
- FinBERT: Financial Sentiment Analysis
|
177 |
- Falcon: Strategic Recommendations
|
178 |
|
179 |
-
|
|
|
|
|
|
|
180 |
examples=[
|
181 |
[
|
182 |
"OFINTECH-Income Statement-template.csv",
|
183 |
-
"OFINTECH Balance Sheet template.csv"
|
|
|
184 |
]
|
185 |
]
|
186 |
)
|
|
|
1 |
import gradio as gr
|
2 |
import pandas as pd
|
3 |
+
from transformers import pipeline
|
4 |
import torch
|
5 |
+
import PyPDF2
|
6 |
+
import io
|
7 |
+
|
8 |
+
class FinancialAnalyzer:
|
9 |
+
def __init__(self):
|
10 |
+
"""Initialize models"""
|
11 |
+
# 1. Llama 2 for strategic analysis
|
12 |
+
self.strategic_analyzer = pipeline(
|
13 |
+
"text-generation",
|
14 |
+
model="meta-llama/Llama-2-7b-chat-hf",
|
15 |
+
device_map="auto"
|
16 |
+
)
|
17 |
+
|
18 |
+
# 2. FinBERT for financial sentiment
|
19 |
+
self.financial_analyzer = pipeline(
|
20 |
"text-classification",
|
21 |
model="ProsusAI/finbert",
|
22 |
return_all_scores=True
|
23 |
)
|
|
|
24 |
|
25 |
+
# 3. Falcon for recommendations
|
26 |
+
self.recommendation_generator = pipeline(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
"text-generation",
|
28 |
+
model="tiiuae/falcon-7b-instruct",
|
|
|
29 |
device_map="auto"
|
30 |
)
|
31 |
+
|
32 |
+
def extract_text_from_pdf(self, pdf_file):
|
33 |
+
"""Extract text from PDF file"""
|
34 |
+
try:
|
35 |
+
pdf_reader = PyPDF2.PdfReader(pdf_file)
|
36 |
+
text = ""
|
37 |
+
for page in pdf_reader.pages:
|
38 |
+
text += page.extract_text() + "\n"
|
39 |
+
return text
|
40 |
+
except Exception as e:
|
41 |
+
print(f"Error extracting PDF text: {str(e)}")
|
42 |
+
return None
|
43 |
+
|
44 |
+
def generate_strategic_analysis(self, financial_data, kpi_data=None):
|
45 |
+
"""Generate strategic analysis using Llama 2"""
|
46 |
+
# Include KPI data if available
|
47 |
+
kpi_section = f"\nKPI Information:\n{kpi_data}" if kpi_data else ""
|
48 |
|
49 |
+
prompt = f"""[INST] As a senior financial analyst, analyze these financial statements and KPIs:
|
50 |
+
|
51 |
+
Financial Data:
|
52 |
+
{financial_data}
|
53 |
+
{kpi_section}
|
54 |
+
|
55 |
+
Provide a comprehensive analysis including:
|
56 |
+
1. Business Health Assessment
|
57 |
+
2. Key Strategic Insights
|
58 |
+
3. Market Position Analysis
|
59 |
+
4. Growth Opportunities
|
60 |
+
5. Risk Factors
|
61 |
+
6. KPI Performance and Trends
|
62 |
+
7. Financial Ratio Analysis
|
63 |
+
8. Operational Efficiency Assessment [/INST]"""
|
64 |
+
|
65 |
+
response = self.strategic_analyzer(
|
66 |
+
prompt,
|
67 |
+
max_length=1500, # Increased for more comprehensive analysis
|
68 |
+
temperature=0.7
|
69 |
+
)
|
70 |
+
return response[0]['generated_text']
|
71 |
+
|
72 |
+
def analyze_sentiment(self, text):
|
73 |
+
"""Analyze financial sentiment using FinBERT"""
|
74 |
+
return self.financial_analyzer(text)
|
75 |
+
|
76 |
+
def generate_recommendations(self, analysis, kpi_data=None):
|
77 |
+
"""Generate recommendations using Falcon"""
|
78 |
+
kpi_context = f"\nKPI Context:\n{kpi_data}" if kpi_data else ""
|
79 |
+
|
80 |
+
prompt = f"""Based on this financial analysis and KPI data:
|
81 |
+
{analysis}
|
82 |
+
{kpi_context}
|
83 |
+
|
84 |
+
Provide specific, actionable recommendations covering:
|
85 |
+
1. Strategic Initiatives
|
86 |
+
2. Operational Improvements
|
87 |
+
3. Financial Management
|
88 |
+
4. Risk Mitigation
|
89 |
+
5. Growth Strategy
|
90 |
+
6. KPI Optimization
|
91 |
+
7. Performance Enhancement
|
92 |
+
8. Resource Allocation"""
|
93 |
+
|
94 |
+
response = self.recommendation_generator(
|
95 |
+
prompt,
|
96 |
+
max_length=1000,
|
97 |
+
temperature=0.6
|
98 |
+
)
|
99 |
+
return response[0]['generated_text']
|
100 |
|
101 |
+
def analyze_financial_statements(income_statement, balance_sheet, kpi_pdf=None):
|
102 |
+
"""Main analysis function"""
|
103 |
try:
|
104 |
+
# Read financial statements
|
105 |
income_df = pd.read_csv(income_statement.name)
|
106 |
balance_df = pd.read_csv(balance_sheet.name)
|
107 |
|
108 |
+
# Initialize analyzer
|
109 |
+
analyzer = FinancialAnalyzer()
|
110 |
|
111 |
+
# Extract KPI data if provided
|
112 |
+
kpi_data = None
|
113 |
+
if kpi_pdf:
|
114 |
+
kpi_data = analyzer.extract_text_from_pdf(kpi_pdf.name)
|
115 |
|
116 |
+
# Prepare financial data
|
117 |
+
financial_data = f"""
|
118 |
+
Income Statement Summary:
|
119 |
+
{income_df.to_string()}
|
120 |
|
121 |
+
Balance Sheet Summary:
|
122 |
+
{balance_df.to_string()}
|
123 |
+
"""
|
124 |
+
|
125 |
+
# Generate strategic analysis
|
126 |
+
strategic_analysis = analyzer.generate_strategic_analysis(financial_data, kpi_data)
|
127 |
+
|
128 |
+
# Analyze sentiment
|
129 |
+
sentiment = analyzer.analyze_sentiment(strategic_analysis)
|
130 |
+
|
131 |
+
# Generate recommendations
|
132 |
+
recommendations = analyzer.generate_recommendations(strategic_analysis, kpi_data)
|
133 |
+
|
134 |
+
# Format output
|
135 |
+
output = format_results(strategic_analysis, sentiment, recommendations, kpi_data)
|
136 |
+
|
137 |
+
return output
|
138 |
|
139 |
except Exception as e:
|
140 |
return f"Error analyzing files: {str(e)}"
|
141 |
|
142 |
+
def format_results(analysis, sentiment, recommendations, kpi_data=None):
|
143 |
+
"""Format analysis results"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
144 |
output = "# Financial Analysis Report\n\n"
|
145 |
|
146 |
# Strategic Analysis
|
147 |
output += "## Strategic Analysis\n\n"
|
148 |
+
output += analysis.split('[/INST]')[-1].strip() + "\n\n"
|
149 |
+
|
150 |
+
# KPI Analysis (if available)
|
151 |
+
if kpi_data:
|
152 |
+
output += "## KPI Analysis\n\n"
|
153 |
+
output += "Analysis includes KPI data from provided documentation.\n\n"
|
154 |
|
155 |
+
# Sentiment Analysis
|
156 |
output += "## Market Sentiment\n\n"
|
157 |
+
for score in sentiment[0]:
|
158 |
output += f"- {score['label']}: {score['score']:.2%}\n"
|
159 |
output += "\n"
|
160 |
|
161 |
# Recommendations
|
162 |
output += "## Strategic Recommendations\n\n"
|
163 |
+
output += recommendations
|
164 |
|
165 |
return output
|
166 |
|
|
|
169 |
fn=analyze_financial_statements,
|
170 |
inputs=[
|
171 |
gr.File(label="Income Statement (CSV)"),
|
172 |
+
gr.File(label="Balance Sheet (CSV)"),
|
173 |
+
gr.File(label="KPI Documentation (PDF, Optional)", file_types=[".pdf"])
|
174 |
],
|
175 |
outputs=gr.Markdown(),
|
176 |
title="AI-Powered Financial Statement Analysis",
|
177 |
+
description="""Upload your financial statements and optional KPI documentation for comprehensive analysis using:
|
178 |
+
- Llama 2: Strategic Analysis
|
179 |
- FinBERT: Financial Sentiment Analysis
|
180 |
- Falcon: Strategic Recommendations
|
181 |
|
182 |
+
Supports:
|
183 |
+
- Income Statement (CSV)
|
184 |
+
- Balance Sheet (CSV)
|
185 |
+
- KPI Documentation (PDF)""",
|
186 |
examples=[
|
187 |
[
|
188 |
"OFINTECH-Income Statement-template.csv",
|
189 |
+
"OFINTECH Balance Sheet template.csv",
|
190 |
+
None # Optional KPI PDF
|
191 |
]
|
192 |
]
|
193 |
)
|