A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.
audit: fix personal_finance_agent - add docstrings, PDF support, bar chart, clear data button, download chat history, fix formatting, improve response speed
Tiioluwani832e4d950e1d
diff --git a/ai_agents/personal_finance_agent/README.md b/ai_agents/personal_finance_agent/README.mdindex 17ba925..d688def 100644--- a/ai_agents/personal_finance_agent/README.md+++ b/ai_agents/personal_finance_agent/README.md@@ -12,11 +12,14 @@ Personal Finance Agent is a Streamlit application that ingests transaction CSVs,## Features-- CSV upload for bank exports with flexible column names (date, description, amount, or debit/credit)+- CSV and PDF upload for bank exports with flexible column names (date, description, amount, or debit/credit)- Automatic categorization into Food, Transport, Entertainment, Utilities, Shopping, Health, and Other- SQLite persistence for fast queries and agent tool access- Natural language Q&A via a LangChain agent with pandas summaries and read-only SQL tools- Weekly budget suggestions derived from your spending patterns+- Spending breakdown bar chart displayed in the sidebar after upload+- Clear Data button to wipe the loaded data and start fresh+- Download chat history as a `.txt` file after each agent response- Bundled sample data (`transactions.csv`) so you can try the app without uploading a bank statement- Orq.ai model routing through the OpenAI SDK with `deepseek-v4-flash` by default@@ -34,6 +37,7 @@ Additional Tools:- Database: SQLite- Data Processing: pandas+- PDF Parsing: [PyMuPDF](https://pymupdf.readthedocs.io/)- Web Framework: Streamlit## Prerequisites@@ -97,7 +101,9 @@ On Windows Command Prompt, use `copy .env.example .env` instead of `cp`.streamlit run app.py```-Open the local URL shown in the terminal (typically `http://localhost:8501`). In the sidebar, click **Load sample transactions.csv** or upload your own CSV, then ask questions in the chat or use the sample prompt buttons.+Open the local URL shown in the terminal (typically `http://localhost:8501`). In the sidebar, click **Load sample transactions.csv** or upload your own CSV or PDF bank statement, then ask questions in the chat or use the sample prompt buttons.++> **Note:** PDF files must be text-based (digitally generated) for text extraction to work. Scanned or image-only PDFs will not produce usable transaction data.### Example Usagediff --git a/ai_agents/personal_finance_agent/agent.py b/ai_agents/personal_finance_agent/agent.pyindex 3e0ccf4..b20faeb 100644--- a/ai_agents/personal_finance_agent/agent.py+++ b/ai_agents/personal_finance_agent/agent.py@@ -2,6 +2,8 @@from __future__ import annotations+import functools+import jsonimport osimport reimport sqlite3@@ -95,6 +97,7 @@ def _parse_amount(row: pd.Series) -> float:def categorize_transaction(description: str, amount: float) -> str:+ """Return the spending category for a transaction based on keyword matching."""text = (description or "").lower()if amount > 0 and any(k in text for k in INCOME_KEYWORDS):return "Other"@@ -179,7 +182,82 @@ def ingest_csv(file_path: str | Path, replace: bool = True) -> dict[str, Any]:}+def parse_pdf_to_dataframe(pdf_path: str | Path) -> pd.DataFrame:+ """Extract transactions from a PDF bank statement via pdfplumber and the LLM, returning a date/description/amount DataFrame."""+ import fitz++ doc = fitz.open(str(Path(pdf_path)))+ pages_text = []+ for page_num in range(len(doc)):+ page = doc[page_num]+ t = page.get_text()+ if not t.strip():+ raw_dict = page.get_text("rawdict")+ t = " ".join(+ span["text"]+ for block in raw_dict.get("blocks", [])+ for line in block.get("lines", [])+ for span in line.get("spans", [])+ if span.get("text", "").strip()+ )+ pages_text.append(t)+ doc.close()+ text = "\n".join(pages_text)++ if not text.strip():+ print("WARNING: no text extracted from PDF - the file may be a scanned image.")++ api_key = os.getenv("ORQ_API_KEY")+ if not api_key:+ raise ValueError("ORQ_API_KEY is not set. Copy .env.example to .env and add your key.")++ client = OpenAI(base_url="https://api.orq.ai/v3/router", api_key=api_key)+ model = os.getenv("ORQ_MODEL", "deepseek-v4-flash")++ print("--- pymupdf extracted text ---")+ print(text)+ print("--- end extracted text ---")++ prompt = (+ "You are a bank statement parser. Read the bank statement text below and identify "+ "every transaction regardless of the column names, layout, or format used. "+ "For each transaction extract: a date, a short description or merchant name, and a "+ "single amount (negative for money going out, positive for money coming in). "+ "If the statement uses separate debit and credit columns, combine them into one amount. "+ "Return ONLY a JSON array where every object has exactly these three keys: "+ "\"date\" (YYYY-MM-DD string), \"description\" (string), \"amount\" (number). "+ "Do not include any explanation, notes, markdown, or text outside the JSON array.\n\n"+ f"Bank statement text:\n{text}"+ )++ response = client.chat.completions.create(+ model=model,+ messages=[{"role": "user", "content": prompt}],+ max_tokens=4096,+ )++ raw = (response.choices[0].message.content or "").strip()+ raw = re.sub(r"^```[^\n]*\n?", "", raw)+ raw = re.sub(r"```$", "", raw.strip())++ try:+ records = json.loads(raw.strip())+ if not isinstance(records, list):+ raise ValueError("Response is not a JSON array")+ df = pd.DataFrame(records)+ if not {"date", "description", "amount"}.issubset(df.columns):+ raise ValueError("Missing required columns in parsed response")+ except Exception:+ raise ValueError(+ "Could not parse PDF as a bank statement. Please ensure it contains "+ "transaction data with dates, descriptions and amounts."+ )++ return df[["date", "description", "amount"]]++def load_transactions_df() -> pd.DataFrame:+ """Load all transactions from SQLite into a DataFrame, returning empty if no DB exists."""if not DB_PATH.exists():return pd.DataFrame(columns=["id", "date", "description", "amount", "category", "is_income"]@@ -233,6 +311,7 @@ def _format_weekly_budget() -> str:def get_llm():+ """Instantiate and return the ChatOpenAI client pointed at the Orq.ai router."""from langchain_openai import ChatOpenAIapi_key = os.getenv("ORQ_API_KEY")@@ -388,10 +467,14 @@ For vague questions like "unnecessary expenses", use find_largest_discretionary_Be concise, use USD formatting, and cite figures from tool results. If no data is loaded, tell the user to upload a CSV.Today's reference date for relative periods is {today}.++Always format responses using proper markdown: use **bold** (no spaces between asterisks and text) for key figures and category names, use bullet points for lists, and use clean line breaks between sections for readability."""[email protected]_cache(maxsize=1)def build_agent_graph():+ """Build and return the LangChain tool-calling agent graph with the finance tools."""from langchain.agents import create_agentllm = get_llm()@@ -417,6 +500,7 @@ def ask_finance_agent(question: str,chat_history: list[tuple[str, str]] | None = None,) -> str:+ """Run the finance agent on a question and return its plain-text reply."""from langchain_core.messages import AIMessage, HumanMessagegraph = build_agent_graph()diff --git a/ai_agents/personal_finance_agent/app.py b/ai_agents/personal_finance_agent/app.pyindex 16d028b..9acd077 100644--- a/ai_agents/personal_finance_agent/app.py+++ b/ai_agents/personal_finance_agent/app.py@@ -2,16 +2,20 @@from __future__ import annotations+import osimport tempfile+import tracebackimport streamlit as stfrom dotenv import load_dotenvfrom agent import (+ DB_PATH,SAMPLE_CSV,ask_finance_agent,ingest_csv,load_transactions_df,+ parse_pdf_to_dataframe,)load_dotenv()@@ -42,9 +46,9 @@ def _render_sidebar() -> None:with st.sidebar:st.header("Data")uploaded = st.file_uploader(- "Upload bank statement or transaction CSV",- type=["csv"],- help="CSV should include date, description, and amount (or debit/credit columns).",+ "Upload bank statement or transaction CSV/PDF",+ type=["csv", "pdf"],+ help="CSV should include date, description, and amount (or debit/credit columns). PDF bank statements are also supported.",)if st.button("Load sample transactions.csv", use_container_width=True):@@ -54,10 +58,22 @@ def _render_sidebar() -> None:st.success(f"Loaded {summary['rows_imported']} sample transactions.")if uploaded is not None:- with tempfile.NamedTemporaryFile(delete=False, suffix=".csv") as tmp:+ is_pdf = uploaded.name.lower().endswith(".pdf")+ suffix = ".pdf" if is_pdf else ".csv"+ with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:tmp.write(uploaded.getvalue())temp_path = tmp.nametry:+ if is_pdf:+ try:+ pdf_df = parse_pdf_to_dataframe(temp_path)+ fd, csv_path = tempfile.mkstemp(suffix=".csv")+ os.close(fd)+ pdf_df.to_csv(csv_path, index=False)+ temp_path = csv_path+ except Exception:+ traceback.print_exc()+ raisesummary = ingest_csv(temp_path, replace=True)st.session_state.data_loaded = Truest.session_state.import_summary = summary@@ -66,7 +82,7 @@ def _render_sidebar() -> None:f"({summary['date_range']}).")except Exception as exc:- st.error(f"Could not parse CSV: {exc}")+ st.error(f"Could not parse file: {exc}")if st.session_state.get("data_loaded"):summary = st.session_state.get("import_summary", {})@@ -77,6 +93,14 @@ def _render_sidebar() -> None:st.caption("Category totals")for cat, val in breakdown.items():st.write(f"**{cat}:** ${val:,.2f}")+ st.bar_chart(breakdown)++ if st.button("Clear Data", use_container_width=True, type="secondary"):+ if DB_PATH.exists():+ DB_PATH.unlink()+ for key in list(st.session_state.keys()):+ del st.session_state[key]+ st.rerun()def _render_transactions_preview() -> None:@@ -125,7 +149,7 @@ def main() -> None:st.markdown(prompt)with st.chat_message("assistant"):- with st.spinner("Analyzing your transactions..."):+ with st.spinner("Analyzing your finances..."):history: list[tuple[str, str]] = []prior = st.session_state.messages[:-1]idx = 0@@ -146,6 +170,17 @@ def main() -> None:"`deepseek-v4-flash` available.")st.markdown(answer)+ chat_export = "\n\n".join(+ f"{m['role'].upper()}: {m['content']}"+ for m in st.session_state.messages[:-1] + [{"role": "assistant", "content": answer}]+ )+ st.download_button(+ label="Download chat history",+ data=chat_export,+ file_name="chat_history.txt",+ mime="text/plain",+ key=f"download_{len(st.session_state.messages)}",+ )st.session_state.messages.append({"role": "assistant", "content": answer})diff --git a/ai_agents/personal_finance_agent/finance.db b/ai_agents/personal_finance_agent/finance.dbnew file mode 100644index 0000000..9edf6d3Binary files /dev/null and b/ai_agents/personal_finance_agent/finance.db differdiff --git a/ai_agents/personal_finance_agent/requirements.txt b/ai_agents/personal_finance_agent/requirements.txtindex 0487b55..70240f8 100644--- a/ai_agents/personal_finance_agent/requirements.txt+++ b/ai_agents/personal_finance_agent/requirements.txt@@ -6,3 +6,4 @@ langchain-core>=0.3.0langgraph>=0.2.0openai>=1.40.0python-dotenv>=1.0.0+pymupdf>=1.24.0