-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
229 lines (180 loc) · 7.19 KB
/
Copy pathapp.py
File metadata and controls
229 lines (180 loc) · 7.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
from flask import Flask, redirect, url_for, session, render_template, request, jsonify
from google_auth_oauthlib.flow import Flow
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
import os
import json
import datetime
import requests
app = Flask(__name__)
app.secret_key = "your_secret_key"
DATA_FILE = 'data/finances.json'
os.makedirs('data', exist_ok=True)
if not os.path.exists(DATA_FILE):
with open(DATA_FILE, 'w') as f:
json.dump([], f)
# Google OAuth Configuration
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
GOOGLE_CLIENT_SECRETS_FILE = "credentials.json"
SCOPES = [
"https://www.googleapis.com/auth/tasks",
"https://www.googleapis.com/auth/calendar.readonly"
]
flow = Flow.from_client_secrets_file(
GOOGLE_CLIENT_SECRETS_FILE,
scopes=SCOPES,
redirect_uri="http://127.0.0.1:5000/callback"
)
# UTILITY FUNCTIONS
def load_transactions():
if os.path.exists(DATA_FILE):
with open(DATA_FILE, 'r') as f:
return json.load(f)
return []
def save_transactions(transactions):
with open(DATA_FILE, 'w') as f:
json.dump(transactions, f, indent=4)
def calculate_summary(transactions):
income = sum(float(t['amount']) for t in transactions if t['type'] == 'income')
expense = sum(float(t['amount']) for t in transactions if t['type'] == 'expense')
return {
"income": income,
"expense": expense,
"balance": income - expense
}
# ROUTES
@app.route("/")
def home():
transactions = load_transactions()
summary = calculate_summary(transactions)
# Calculate summary
total_income = sum(float(t["amount"]) for t in transactions if t["type"] == "income")
total_expense = sum(float(t["amount"]) for t in transactions if t["type"] == "expense")
balance = total_income - total_expense
tasks = []
events = []
if "credentials" in session:
credentials = Credentials.from_authorized_user_info(session["credentials"])
if not credentials.valid:
return redirect(url_for("login"))
# Google Tasks
tasks_service = build("tasks", "v1", credentials=credentials)
task_lists = tasks_service.tasklists().list().execute()
for task_list in task_lists.get("items", []):
task_items = tasks_service.tasks().list(tasklist=task_list["id"]).execute().get("items", [])
tasks.append({
"name": task_list["title"],
"id": task_list["id"],
"tasks": task_items
})
# Google Calendar
calendar_service = build("calendar", "v3", credentials=credentials)
now = datetime.datetime.utcnow().isoformat() + "Z"
page_token = None
while True:
events_result = calendar_service.events().list(
calendarId='primary',
timeMin=now,
singleEvents=True,
orderBy='startTime',
pageToken=page_token
).execute()
events.extend(events_result.get('items', []))
page_token = events_result.get('nextPageToken')
if not page_token:
break
return render_template("index.html", tasks=tasks, events=events, transactions=transactions, summary=summary, logged_in="credentials" in session)
@app.route('/')
def index():
transactions = load_transactions()
total_income = sum(float(t["amount"]) for t in transactions if t["type"] == "income")
total_expense = sum(float(t["amount"]) for t in transactions if t["type"] == "expense")
balance = total_income - total_expense
return render_template('index.html', transactions=transactions, total_income=total_income, total_expense=total_expense, balance=balance)
@app.route('/add_transaction', methods=['POST'])
def add_transaction():
data = request.json
transactions = load_transactions()
transactions.append(data)
save_transactions(transactions)
total_income = sum(float(t["amount"]) for t in transactions if t["type"] == "income")
total_expense = sum(float(t["amount"]) for t in transactions if t["type"] == "expense")
balance = total_income - total_expense
return jsonify({
'status': 'success',
'total_income': total_income,
'total_expense': total_expense,
'balance': balance
})
@app.route("/login")
def login():
session.clear()
auth_url, _ = flow.authorization_url(prompt="consent", access_type="offline")
return redirect(auth_url)
@app.route("/callback")
def callback():
flow.fetch_token(authorization_response=request.url)
credentials = flow.credentials
session["credentials"] = json.loads(credentials.to_json())
return redirect(url_for("home"))
@app.route("/logout")
def logout():
session.clear()
return redirect(url_for("home"))
@app.route("/toggle_task", methods=["POST"])
def toggle_task():
if "credentials" not in session:
return redirect(url_for("login"))
credentials = Credentials.from_authorized_user_info(session["credentials"])
tasks_service = build("tasks", "v1", credentials=credentials)
task_id = request.form.get("task_id")
tasklist_id = request.form.get("tasklist_id")
checked = request.form.get("status") == "on"
if not task_id or not tasklist_id:
return "Missing task ID or task list ID", 400
task = tasks_service.tasks().get(tasklist=tasklist_id, task=task_id).execute()
if checked:
task["status"] = "completed"
task["completed"] = datetime.datetime.utcnow().isoformat() + "Z"
else:
task["status"] = "needsAction"
task.pop("completed", None)
tasks_service.tasks().update(tasklist=tasklist_id, task=task_id, body=task).execute()
return redirect(url_for("home"))
@app.route('/chat', methods=['POST'])
def chat():
user_message = request.json.get('message', '').lower()
# Simple hardcoded replies
if "hello" in user_message:
reply = "Hello! How can I assist you today?"
elif "balance" in user_message:
transactions = load_transactions()
summary = calculate_summary(transactions)
reply = f"Your balance is ₹{summary['balance']:.2f}"
elif "tasks" in user_message:
reply = "You can check your tasks in the tasks section above."
elif "bye" in user_message:
reply = "Goodbye! Let me know if you need anything else."
else:
reply = "I'm still learning! Try asking about your balance or say hello."
return jsonify({ "reply": reply })
@app.route("/weather")
def weather():
api_key = "ce9b392cfd5b87bf62f12f96ef7425d3"
city = "dehradun"
url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
try:
res = requests.get(url)
data = res.json()
if data.get("cod") != 200:
return jsonify({"error": "Could not fetch weather data."})
weather_info = {
"city": data["name"],
"description": data["weather"][0]["description"].title(),
"temp": data["main"]["temp"]
}
return jsonify(weather_info)
except Exception as e:
return jsonify({"error": "Failed to fetch weather."})
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=5000)