Rahul2298 commited on
Commit
7c2007f
Β·
verified Β·
1 Parent(s): a615e41

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +85 -153
src/streamlit_app.py CHANGED
@@ -1,158 +1,90 @@
1
- import re
2
- from dataclasses import dataclass
3
- from typing import List, Dict, Optional
4
- import pandas as pd
5
- import streamlit as st
6
  import os
7
- api_key = os.getenv("OPENAI_API_KEY")
8
- print("API key loaded?", bool(api_key))
9
- # from dotenv import load_dotenv
10
- # load_dotenv()
11
-
12
- # HuggingFace optional
13
- try:
14
- from transformers import pipeline
15
- HF_AVAILABLE = True
16
- except Exception:
17
- HF_AVAILABLE = False
18
-
19
- # OpenAI
20
- try:
21
- from openai import OpenAI
22
- OPENAI_AVAILABLE = True
23
- except Exception:
24
- OPENAI_AVAILABLE = False
25
-
26
- # Load environment variables
27
- # load_dotenv()
28
- OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
29
- MODEL = os.getenv("MODEL", "gpt-3.5-turbo")
30
-
31
- # Streamlit config
32
- st.set_page_config(page_title="Personal Finance Chatbot", page_icon="πŸ’¬", layout="wide")
33
-
34
- @dataclass
35
- class FinanceRecord:
36
- date: str
37
- description: str
38
- amount: float
39
- category: Optional[str] = None
40
-
41
- class HuggingFaceProvider:
42
- def __init__(self):
43
- self.available = HF_AVAILABLE
44
- self.name = "huggingface"
45
- self.generator = None
46
- if self.available:
47
- try:
48
- self.generator = pipeline("text2text-generation", model="google/flan-t5-small")
49
- except Exception:
50
- self.available = False
51
-
52
- def ok(self):
53
- return self.available and self.generator is not None
54
-
55
- def generate(self, prompt: str, max_tokens: int = 256):
56
- if not self.ok():
57
- return "[HF provider unavailable]"
58
- try:
59
- result = self.generator(prompt, max_length=max_tokens, do_sample=True)
60
- return result[0]['generated_text']
61
- except Exception as e:
62
- return f"[HF error] {e}"
63
-
64
- class GraniteWatsonProvider:
65
- def __init__(self):
66
- self.name = "granite_watson"
67
-
68
- def ok(self):
69
- return True
70
-
71
- def generate(self, prompt: str, max_tokens: int = 256):
72
- return "[Granite/Watson] This is a placeholder response. Connect IBM SDK here."
73
-
74
- class OpenAIProvider:
75
- def __init__(self):
76
- self.api_key = OPENAI_API_KEY
77
- self.model = MODEL
78
- self.client = None
79
- if self.api_key and OPENAI_AVAILABLE:
80
- try:
81
- self.client = OpenAI(api_key=self.api_key)
82
- except Exception:
83
- self.client = None
84
- self.name = "openai"
85
-
86
- def ok(self):
87
- return self.client is not None
88
-
89
- def generate(self, prompt: str, max_tokens: int = 512):
90
- if not self.client:
91
- return "[OpenAI] API not configured. Please set OPENAI_API_KEY in your environment."
92
- try:
93
- resp = self.client.chat.completions.create(
94
- model=self.model,
95
- messages=[
96
- {"role": "system", "content": "You are a financial assistant."},
97
- {"role": "user", "content": prompt},
98
- ],
99
- max_tokens=max_tokens,
100
- temperature=0.7,
101
- )
102
- return resp.choices[0].message.content.strip()
103
- except Exception as e:
104
- return f"[OpenAI error] {e}"
105
-
106
- def categorize_with_ai(provider, description: str):
107
- prompt = f"Categorize this financial transaction description into: Food, Rent, Utilities, Entertainment, Transport, Other.\nDescription: {description}\nCategory:"
108
- return provider.generate(prompt)
109
-
110
- def get_ai_suggestions(provider, records: List[FinanceRecord]):
111
- df = pd.DataFrame([r.__dict__ for r in records])
112
- prompt = (
113
- "You are a financial advisor. Here are the user's transactions:\n"
114
- f"{df.to_string(index=False)}\n\n"
115
- "Provide insights and suggestions to improve savings and manage money better."
116
- )
117
- return provider.generate(prompt, max_tokens=400)
118
-
119
- # Streamlit UI
120
- st.title("πŸ’¬ Personal Finance Chatbot")
121
- st.write("Manage savings, taxes, and investments with AI guidance.")
122
 
123
- provider_choice = st.selectbox("AI Provider", ["HuggingFace", "Granite/Watson", "OpenAI"], index=0)
 
124
 
125
- hf_provider = HuggingFaceProvider()
126
- granite_provider = GraniteWatsonProvider()
127
- openai_provider = OpenAIProvider()
 
128
 
129
- if provider_choice == "HuggingFace":
130
- provider = hf_provider
131
- elif provider_choice == "Granite/Watson":
132
- provider = granite_provider
133
- else:
134
- provider = openai_provider
135
-
136
- if "records" not in st.session_state:
137
- st.session_state.records: List[FinanceRecord] = []
138
-
139
- st.sidebar.header("Add Transaction")
140
- date = st.sidebar.text_input("Date", "2025-08-30")
141
- description = st.sidebar.text_input("Description", "")
142
- amount = st.sidebar.number_input("Amount", 0.0, 1e9, step=100.0)
143
- if st.sidebar.button("Add Record"):
144
- record = FinanceRecord(date=date, description=description, amount=amount)
145
- record.category = categorize_with_ai(provider, record.description)
146
- st.session_state.records.append(record)
147
- st.sidebar.success("Record added!")
148
-
149
- if st.session_state.records:
150
- st.subheader("Transaction Records")
151
- df = pd.DataFrame([r.__dict__ for r in st.session_state.records])
152
- st.dataframe(df)
153
-
154
- st.subheader("AI Suggestions")
155
- suggestions = get_ai_suggestions(provider, st.session_state.records)
156
- st.write(suggestions)
157
  else:
158
- st.info("No records yet. Add transactions from the sidebar.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
+ import streamlit as st
3
+ import pandas as pd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
+ # βœ… OpenAI client
6
+ from openai import OpenAI
7
 
8
+ # -------------------------------------------------------------------
9
+ # Load API Key securely
10
+ # -------------------------------------------------------------------
11
+ api_key = os.getenv("OPENAI_API_KEY")
12
 
13
+ def mask_key(key: str) -> str:
14
+ """Return a masked version of the API key (safe for logs)."""
15
+ if not key:
16
+ return "❌ No Key Found"
17
+ return key[:6] + "..." + key[-4:]
18
+
19
+ if not api_key:
20
+ st.error("❌ OPENAI_API_KEY is not set. Please add it in Hugging Face β†’ Settings β†’ Variables and secrets.")
21
+ st.stop()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  else:
23
+ st.sidebar.success(f"πŸ”‘ API key loaded: {mask_key(api_key)}")
24
+
25
+ # Initialize OpenAI client
26
+ client = OpenAI(api_key=api_key)
27
+
28
+ # -------------------------------------------------------------------
29
+ # Streamlit App UI
30
+ # -------------------------------------------------------------------
31
+ st.set_page_config(page_title="πŸ’° Personal Finance Chatbot", page_icon="πŸ’¬", layout="wide")
32
+
33
+ st.title("πŸ’¬ Personal Finance Chatbot")
34
+ st.write("Get intelligent guidance for **savings, taxes, and investments** using OpenAI.")
35
+
36
+ # Store chat history
37
+ if "messages" not in st.session_state:
38
+ st.session_state["messages"] = []
39
+
40
+ # -------------------------------------------------------------------
41
+ # Finance transaction tracker
42
+ # -------------------------------------------------------------------
43
+ if "transactions" not in st.session_state:
44
+ st.session_state["transactions"] = []
45
+
46
+ st.sidebar.header("πŸ“Š Add Transaction")
47
+ amount = st.sidebar.number_input("Amount", min_value=0.0, format="%.2f")
48
+ category = st.sidebar.selectbox("Category", ["Savings", "Investment", "Tax", "Expense"])
49
+ if st.sidebar.button("Add Transaction"):
50
+ st.session_state["transactions"].append({"Amount": amount, "Category": category})
51
+ st.sidebar.success("βœ… Transaction added!")
52
+
53
+ if st.session_state["transactions"]:
54
+ df = pd.DataFrame(st.session_state["transactions"])
55
+ st.sidebar.subheader("πŸ’΅ Transactions")
56
+ st.sidebar.dataframe(df)
57
+
58
+ # -------------------------------------------------------------------
59
+ # Chatbot interaction
60
+ # -------------------------------------------------------------------
61
+ st.subheader("πŸ’‘ Ask me anything about your finances")
62
+
63
+ user_input = st.text_input("Type your question here:")
64
+ if st.button("Send") and user_input:
65
+ # Store user message
66
+ st.session_state["messages"].append({"role": "user", "content": user_input})
67
+
68
+ # Call OpenAI API
69
+ try:
70
+ response = client.chat.completions.create(
71
+ model="gpt-4o-mini",
72
+ messages=st.session_state["messages"],
73
+ max_tokens=500,
74
+ temperature=0.7,
75
+ )
76
+
77
+ bot_reply = response.choices[0].message.content
78
+ st.session_state["messages"].append({"role": "assistant", "content": bot_reply})
79
+
80
+ except Exception as e:
81
+ st.error(f"⚠️ Error: {str(e)}")
82
+
83
+ # -------------------------------------------------------------------
84
+ # Display conversation
85
+ # -------------------------------------------------------------------
86
+ for msg in st.session_state["messages"]:
87
+ if msg["role"] == "user":
88
+ st.markdown(f"**πŸ§‘ You:** {msg['content']}")
89
+ else:
90
+ st.markdown(f"**πŸ€– Bot:** {msg['content']}")