Ujeshhh commited on
Commit
bea8665
Β·
verified Β·
1 Parent(s): 1a6a3e5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +101 -42
app.py CHANGED
@@ -1,52 +1,111 @@
1
  import gradio as gr
2
- import pandas as pd
3
- from extract import extract_upi_transactions
4
- from clean import clean_upi_data
5
- from analysis import analyze_spending_pattern, get_financial_advice
6
- from visualize import plot_spending_by_category
7
 
8
- def process_pdf(file):
9
- """
10
- Process the uploaded PDF UPI transaction statement.
11
- Extracts, cleans, analyzes, and visualizes spending data.
12
- """
13
  try:
14
- # βœ… Step 1: Extract transactions
15
- df = extract_upi_transactions(file.name)
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
- if df is None or df.empty:
18
- return "Error: No transactions found in the uploaded PDF.", "", ""
 
 
19
 
20
- # βœ… Step 2: Clean data
21
- df = clean_upi_data(df)
 
 
 
 
 
 
 
 
 
 
22
 
23
- # βœ… Step 3: Perform financial analysis
24
- analysis = analyze_spending_pattern(df)
 
 
25
 
26
- # βœ… Step 4: Generate financial advice
27
- advice = get_financial_advice(df)
 
 
 
28
 
29
- # βœ… Step 5: Generate spending visualization
30
- plot_spending_by_category(df)
 
 
 
 
 
 
 
 
 
31
 
32
- return df, analysis, advice
33
-
34
  except Exception as e:
35
- return f"Error: {str(e)}", "", ""
36
-
37
- # βœ… Gradio UI
38
- interface = gr.Interface(
39
- fn=process_pdf,
40
- inputs=gr.File(label="Upload UPI PDF Statement"),
41
- outputs=[
42
- gr.Dataframe(label="Processed Transaction Data"),
43
- gr.Textbox(label="Spending Analysis"),
44
- gr.Textbox(label="Financial Advice"),
45
- ],
46
- title="UPI Financial Analyzer",
47
- description="Upload your UPI transaction statement to get insights, trends, and personalized recommendations.",
48
- theme="compact",
49
- )
50
-
51
- if __name__ == "__main__":
52
- interface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import PyPDF2
3
+ import google.generativeai as genai
4
+ import re
5
+ import io
 
6
 
7
+ # πŸ” Gemini API Key
8
+ GEMINI_API_KEY = "AIzaSyDnx_qUjGTFG1pv1otPUhNt_bGGv14aMDI"
9
+ genai.configure(api_key=GEMINI_API_KEY)
10
+
11
+ # πŸ“„ Extract text from PDFdef extract_text_from_pdf(file):
12
  try:
13
+ reader = PyPDF2.PdfReader(file)
14
+ text = ""
15
+ for page in reader.pages:
16
+ content = page.extract_text()
17
+ if content:
18
+ text += content + "\n"
19
+ return text.strip()
20
+ except:
21
+ return ""
22
+
23
+ def extract_section(full_text, label):
24
+ pattern = rf"\*\*\- {re.escape(label)}:\*\*\s*(.*?)(?=\n\*\*|\Z)"
25
+ match = re.search(pattern, full_text, re.DOTALL)
26
+ return match.group(1).strip() if match else "❓ Not found"
27
 
28
+ def analyze_financial_data(file):
29
+ text = extract_text_from_pdf(file)
30
+ if not text:
31
+ return ("⚠️ Failed to extract text. Ensure it’s not a scanned image PDF.", "", "", "", "", "", "", "", None)
32
 
33
+ prompt = f"""
34
+ Analyze the following Paytm transaction history and generate financial insights in the following structure:
35
+ **Financial Insights**
36
+ **- Monthly Income & Expenses:** [data]
37
+ **- Unnecessary Expense Categories:** [data]
38
+ **- Estimated Savings %:** [data]
39
+ **- Spending Trends:** [data]
40
+ **- Category-wise Expense Breakdown (Partial):** [data]
41
+ **- Cost Control Suggestions:** [data]
42
+ Transaction History:
43
+ {text}
44
+ """
45
 
46
+ try:
47
+ model = genai.GenerativeModel("gemini-1.5-flash")
48
+ response = model.generate_content(prompt)
49
+ full_text = response.text.strip()
50
 
51
+ # Generate downloadable report
52
+ report_io = io.StringIO()
53
+ report_io.write(full_text)
54
+ report_bytes = io.BytesIO(report_io.getvalue().encode())
55
+ report_bytes.name = "financial_analysis.txt"
56
 
57
+ return (
58
+ "βœ… Analysis Complete",
59
+ text[:2000] + "..." if len(text) > 2000 else text, # Full text preview
60
+ extract_section(full_text, "Monthly Income & Expenses"),
61
+ extract_section(full_text, "Unnecessary Expense Categories"),
62
+ extract_section(full_text, "Estimated Savings %"),
63
+ extract_section(full_text, "Spending Trends"),
64
+ extract_section(full_text, "Category-wise Expense Breakdown (Partial)"),
65
+ extract_section(full_text, "Cost Control Suggestions"),
66
+ report_bytes
67
+ )
68
 
 
 
69
  except Exception as e:
70
+ return (f"❌ Gemini Error: {e}", "", "", "", "", "", "", "", None)
71
+
72
+ # 🎨 Gradio Interface
73
+ with gr.Blocks(title="AI Finance Assistant") as demo:
74
+ gr.Markdown("## πŸ’° AI-Powered Personal Finance Assistant")
75
+ gr.Markdown("Upload your **Paytm transaction PDF** (text-based only) and get structured financial insights using **Gemini AI**.")
76
+
77
+ with gr.Row():
78
+ with gr.Column():
79
+ pdf_input = gr.File(label="πŸ“‚ Upload PDF", file_types=[".pdf"])
80
+ analyze_btn = gr.Button("πŸ” Analyze My Finances")
81
+
82
+ with gr.Column():
83
+ status = gr.Textbox(label="βœ… Status", interactive=False)
84
+ download_btn = gr.File(label="πŸ“₯ Download Report", interactive=False)
85
+
86
+ with gr.Accordion("πŸ“œ Extracted PDF Text (preview)", open=False):
87
+ pdf_text = gr.Textbox(lines=10, label="Extracted Text", interactive=False)
88
+
89
+ with gr.Row():
90
+ income_box = gr.Textbox(label="πŸ’΅ Monthly Income & Expenses", lines=5, interactive=False)
91
+ unnecessary_box = gr.Textbox(label="πŸ›’ Unnecessary Expenses", lines=5, interactive=False)
92
+
93
+ with gr.Row():
94
+ savings_box = gr.Textbox(label="πŸ’° Estimated Savings %", lines=2, interactive=False)
95
+ trends_box = gr.Textbox(label="πŸ“ˆ Spending Trends", lines=5, interactive=False)
96
+
97
+ with gr.Row():
98
+ breakdown_box = gr.Textbox(label="πŸ“Š Category-wise Breakdown", lines=6, interactive=False)
99
+ suggestion_box = gr.Textbox(label="🧠 Cost Control Suggestions", lines=6, interactive=False)
100
+
101
+ analyze_btn.click(
102
+ fn=analyze_financial_data,
103
+ inputs=pdf_input,
104
+ outputs=[
105
+ status, pdf_text,
106
+ income_box, unnecessary_box, savings_box,
107
+ trends_box, breakdown_box, suggestion_box, download_btn
108
+ ]
109
+ )
110
+
111
+ demo.launch()