Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import PyPDF2 | |
| import google.generativeai as genai | |
| import re | |
| import os | |
| # Load API key safely | |
| GEMINI_API_KEY = os.getenv("GEMINI_API_KEY") # set in environment | |
| 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", "", "", "", "", "", "") | |
| text = text[:6000] # LIMIT TOKENS (IMPORTANT) | |
| prompt = f""" | |
| Analyze Paytm transactions and return structured insights. | |
| **Financial Insights** | |
| **- Monthly Income & Expenses:** ... | |
| **- Unnecessary Expense Categories:** ... | |
| **- Estimated Savings %:** ... | |
| **- Spending Trends:** ... | |
| **- Category-wise Expense Breakdown (Partial):** ... | |
| **- Cost Control Suggestions:** ... | |
| Transaction History: | |
| {text} | |
| """ | |
| try: | |
| model = genai.GenerativeModel("gemini-1.5-flash-latest") | |
| 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"), | |
| gr.Textbox(label="Monthly Income & Expenses"), | |
| gr.Textbox(label="Unnecessary Expense Categories"), | |
| gr.Textbox(label="Estimated Savings %"), | |
| gr.Textbox(label="Spending Trends"), | |
| gr.Textbox(label="Category-wise Breakdown"), | |
| gr.Textbox(label="Cost Control Suggestions"), | |
| ], | |
| ).launch() | |