Spaces:
Sleeping
Sleeping
ο»Ώimport gradio as gr | |
import PyPDF2 | |
import google.generativeai as genai | |
import re | |
GEMINI_API_KEY = "AIzaSyDgb-PyRXrrwuBqnjc3BuXSjbrM7dPlNJY" # Replace with your actual key | |
genai.configure(api_key=GEMINI_API_KEY) | |
def extract_text_from_pdf(file): | |
try: | |
reader = PyPDF2.PdfReader(file) | |
text = "" | |
for page in reader.pages: | |
content = page.extract_text() | |
if content: | |
text += content + "\n" | |
return text.strip() | |
except: | |
return "" | |
def extract_section(full_text, label): | |
pattern = rf"\*\*\- {re.escape(label)}:\*\*\s*(.*?)(?=\n\*\*|\Z)" | |
match = re.search(pattern, full_text, re.DOTALL) | |
return match.group(1).strip() if match else "β Not found" | |
def analyze_financial_data(file): | |
text = extract_text_from_pdf(file) | |
if not text: | |
return ( | |
"β οΈ Failed to extract text from the PDF. Ensure itβs not scanned.", | |
"", "", "", "", "", "" | |
) | |
prompt = f""" | |
Analyze the following Paytm transaction history and generate financial insights in the following structure: | |
**Financial Insights** | |
**- Monthly Income & Expenses:** [data] | |
**- Unnecessary Expense Categories:** [data] | |
**- Estimated Savings %:** [data] | |
**- Spending Trends:** [data] | |
**- Category-wise Expense Breakdown (Partial):** [data] | |
**- Cost Control Suggestions:** [data] | |
Transaction History: | |
{text} | |
""" | |
try: | |
model = genai.GenerativeModel("gemini-1.5-flash") | |
response = model.generate_content(prompt) | |
full_text = response.text.strip() | |
return ( | |
"β Analysis Complete", | |
extract_section(full_text, "Monthly Income & Expenses"), | |
extract_section(full_text, "Unnecessary Expense Categories"), | |
extract_section(full_text, "Estimated Savings %"), | |
extract_section(full_text, "Spending Trends"), | |
extract_section(full_text, "Category-wise Expense Breakdown (Partial)"), | |
extract_section(full_text, "Cost Control Suggestions"), | |
) | |
except Exception as e: | |
return (f"β Gemini Error: {e}", "", "", "", "", "", "") | |
gr.Interface( | |
fn=analyze_financial_data, | |
inputs=gr.File(label="π Upload Paytm PDF", file_types=[".pdf"]), | |
outputs=[ | |
gr.Textbox(label="β Status", lines=2, interactive=False), | |
gr.Textbox(label="π΅ Monthly Income & Expenses", lines=8, interactive=False), | |
gr.Textbox(label="π Unnecessary Expense Categories", lines=8, interactive=False), | |
gr.Textbox(label="π° Estimated Savings %", lines=4, interactive=False), | |
gr.Textbox(label="π Spending Trends", lines=8, interactive=False), | |
gr.Textbox(label="π Category-wise Breakdown", lines=10, interactive=False), | |
gr.Textbox(label="π§ Cost Control Suggestions", lines=8, interactive=False), | |
], | |
title="π° AI-Powered Personal Finance Assistant", | |
description="Upload your Paytm transaction PDF (text-based) and get structured financial insights using Gemini AI.", | |
).launch() | |