mugunthjhs commited on
Commit
8215b2d
Β·
verified Β·
1 Parent(s): f20eb84

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +221 -222
app.py CHANGED
@@ -1,223 +1,222 @@
1
- import streamlit as st
2
- import pandas as pd
3
- from datetime import datetime
4
- import database as db # Assuming your database_utils.py is named database.py
5
- import llm_handler
6
- import sqlite3 # For specific error handling
7
-
8
- # --- Page Configuration ---
9
- st.set_page_config(page_title="AI Task Manager", layout="centered", initial_sidebar_state="collapsed")
10
-
11
- # --- Helper Functions ---
12
- def initialize_session_state():
13
- """Initializes session state variables."""
14
- if "user_name" not in st.session_state: st.session_state.user_name = ""
15
- if "user_email" not in st.session_state: st.session_state.user_email = ""
16
- if "logged_in" not in st.session_state: st.session_state.logged_in = False
17
- if "llm" not in st.session_state:
18
- try:
19
- st.session_state.llm = llm_handler.get_llm()
20
- except ValueError as e:
21
- st.error(f"LLM Initialization Error: {e}. Please ensure GOOGLE_API_KEY is set in .env")
22
- st.stop()
23
-
24
- if "last_interacted_task_details" not in st.session_state:
25
- st.session_state.last_interacted_task_details = None
26
- if "chat_history_for_context" not in st.session_state:
27
- st.session_state.chat_history_for_context = []
28
-
29
- # --- Initialize ---
30
- initialize_session_state()
31
- db.create_db_and_table()
32
- if "table_info" not in st.session_state or st.session_state.get("reload_table_info", False):
33
- st.session_state.table_info = db.get_db_info()
34
- st.session_state.reload_table_info = False
35
-
36
-
37
- # --- UI Sections ---
38
-
39
- if not st.session_state.logged_in:
40
- st.title("AI Task Manager Login")
41
- with st.form("login_form"):
42
- name = st.text_input("Your Name", value=st.session_state.get("user_name_input", ""))
43
- email = st.text_input("Your Email", value=st.session_state.get("user_email_input", ""))
44
- login_button = st.form_submit_button("Login")
45
-
46
- if login_button:
47
- error_messages = []
48
- if not name:
49
- error_messages.append("Please enter your name.")
50
- if not email:
51
- error_messages.append("Please enter your email.")
52
- elif not email.strip().lower().endswith(".com"):
53
- error_messages.append("Invalid email format.")
54
-
55
- if not error_messages:
56
- st.session_state.user_name = name
57
- st.session_state.user_email = email
58
- st.session_state.logged_in = True
59
- st.session_state.user_name_input = name
60
- st.session_state.user_email_input = email
61
- st.session_state.last_interacted_task_details = None
62
- st.session_state.reload_table_info = True
63
- st.rerun()
64
- else:
65
- for msg in error_messages:
66
- st.error(msg)
67
- else:
68
- st.sidebar.header("User Info")
69
- st.sidebar.write(f"πŸ‘€ **Name:** {st.session_state.user_name}")
70
- st.sidebar.write(f"πŸ“§ **Email:** {st.session_state.user_email}")
71
- if st.sidebar.button("Logout"):
72
- st.session_state.logged_in = False
73
- st.session_state.user_name = ""
74
- st.session_state.user_email = ""
75
- st.session_state.last_interacted_task_details = None
76
- st.rerun()
77
-
78
- st.title(f"πŸ“ AI Task Manager for {st.session_state.user_name}")
79
- st.markdown("Enter your task command (e.g., 'I have a meeting at 2pm on next Friday' , 'Show pending tasks').")
80
-
81
- if st.session_state.last_interacted_task_details:
82
- task_ctx = st.session_state.last_interacted_task_details
83
-
84
- # Prepare task context display message
85
- task_name = task_ctx.get('task_name', 'N/A')
86
- task_id = task_ctx.get('id', 'N/A')
87
- due_date = task_ctx.get('due_date', '')
88
- due_time = task_ctx.get('due_time', '')
89
- ctx_display = f"Last task: '{task_name}' (ID: {task_id})"
90
- if due_date:
91
- ctx_display += f" - Due: {due_date}"
92
- if due_time:
93
- ctx_display += f" at {due_time}"
94
- st.caption(ctx_display)
95
-
96
-
97
- user_input_query = st.text_input("Your command:", key="task_input", placeholder="e.g., Add task 'Submit report' due next Friday 3pm category Work")
98
-
99
- if st.button("Process Command", type="primary"):
100
- if not user_input_query:
101
- st.warning("Please enter a command.")
102
- else:
103
- llm = st.session_state.llm
104
- table_info = st.session_state.table_info
105
-
106
- context_str = "None"
107
- if st.session_state.last_interacted_task_details:
108
- details = st.session_state.last_interacted_task_details
109
- context_list = []
110
- if details.get('id'): context_list.append(f"id: {details['id']}")
111
- if details.get('task_name'): context_list.append(f"name: '{details['task_name']}'")
112
- if details.get('due_date'): context_list.append(f"due_date: {details['due_date']}")
113
- if details.get('due_time'): context_list.append(f"due_time: {details['due_time']}")
114
- context_str = f"Task context - {', '.join(context_list)}"
115
-
116
-
117
- with st.spinner("πŸ€– Thinking and generating SQL..."):
118
- try:
119
- generated_sql = llm_handler.generate_sql_query(
120
- llm,
121
- user_input_query,
122
- table_info,
123
- st.session_state.user_name,
124
- st.session_state.user_email,
125
- context_str
126
- )
127
- except Exception as e:
128
- st.error(f"Error generating SQL: {e}")
129
- generated_sql = None
130
-
131
- if generated_sql:
132
- st.write("βš™οΈ **Generated SQL Query:**")
133
- st.code(generated_sql, language="sql")
134
-
135
- is_select_query = generated_sql.strip().upper().startswith("SELECT")
136
- is_insert_query = generated_sql.strip().upper().startswith("INSERT")
137
-
138
- with st.spinner("πŸ’Ύ Executing query..."):
139
- try:
140
- summary_context_for_llm = ""
141
- if is_select_query:
142
- data, columns = db.execute_select_query(generated_sql)
143
- if data:
144
- df = pd.DataFrame(data, columns=columns)
145
- major_display_columns = ['id', 'task_name', 'status', 'category', 'due_date', 'due_time', 'created_at']
146
- display_cols_in_df = [col for col in major_display_columns if col in df.columns]
147
-
148
- if not display_cols_in_df and df.columns.any():
149
- display_cols_in_df = df.columns.tolist()
150
-
151
- if display_cols_in_df:
152
- st.dataframe(df[display_cols_in_df], use_container_width=True)
153
- else:
154
- st.info("The query ran but returned no columns to display.")
155
-
156
- summary_context_for_llm = f"Retrieved {len(data)} task(s)."
157
- if len(data) == 1:
158
- st.session_state.last_interacted_task_details = dict(zip(columns, data[0]))
159
- elif len(data) == 0:
160
- summary_context_for_llm = "No tasks found matching your criteria."
161
- else:
162
- st.info("No tasks found matching your criteria.")
163
- summary_context_for_llm = "No tasks found matching your criteria."
164
- st.session_state.last_interacted_task_details = None
165
-
166
- else:
167
- result = db.execute_dml_query(generated_sql)
168
-
169
- action = "processed"
170
- if is_insert_query:
171
- action = "added"
172
- if result:
173
- inserted_task_details = db.get_task_by_id(result, st.session_state.user_email)
174
- if inserted_task_details:
175
- st.session_state.last_interacted_task_details = inserted_task_details
176
- summary_context_for_llm = f"Task '{inserted_task_details.get('task_name')}' (ID: {result}) was {action}."
177
- else:
178
- summary_context_for_llm = f"Task was {action}, but details couldn't be retrieved post-insertion."
179
- else:
180
- summary_context_for_llm = f"Task addition was attempted but may not have completed as expected (no ID returned)."
181
- elif "UPDATE" in generated_sql.upper():
182
- action = "updated"
183
- summary_context_for_llm = f"Task(s) {action}. {result} row(s) affected."
184
- elif "DELETE" in generated_sql.upper():
185
- action = "deleted"
186
- summary_context_for_llm = f"Task(s) {action}. {result} row(s) affected."
187
- st.session_state.last_interacted_task_details = None
188
-
189
- st.success(f"Task command '{action}' processed successfully.")
190
-
191
-
192
- with st.spinner("πŸ“œ Generating friendly summary..."):
193
- final_summary = llm_handler.summarize_query_result(
194
- llm,
195
- user_input_query,
196
- generated_sql,
197
- summary_context_for_llm
198
- )
199
- st.markdown(f"**πŸ€– Summary:**\n {final_summary}")
200
-
201
- except ValueError as ve:
202
- st.error(f"⚠️ Action failed: {ve}")
203
- except sqlite3.Error as e:
204
- st.error(f"❌ Database Error: {e}")
205
- st.error(f" Failed Query: {generated_sql}")
206
- except Exception as e:
207
- st.error(f"❌ An unexpected error occurred: {e}")
208
- st.error(f" Query attempted: {generated_sql}")
209
-
210
- elif not user_input_query.strip() == "":
211
- st.error("Could not generate an SQL query for your request. Please try rephrasing.")
212
-
213
- st.markdown("---")
214
- st.markdown("Example commands:")
215
- st.caption("""
216
- - Add: "Schedule a 'Team sync meeting' for next Tuesday at 10:00 category Work"
217
- - Add: "I have a 'Doctor's appointment' tomorrow at 3:30 PM"
218
- - View: "Show my tasks for this week", "What's pending?"
219
- - Update: "Mark 'Team sync meeting' as completed" (if it was the last task discussed)
220
- - Update: "I've finished the 'Doctor's appointment'"
221
- - Delete: "Cancel the 'Team sync meeting'"
222
- - Delete: "Remove task 'Old project idea'"
223
  """)
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ from datetime import datetime
4
+ import database as db
5
+ import sqlite3
6
+
7
+ # --- Page Configuration ---
8
+ st.set_page_config(page_title="AI Task Manager", layout="centered", initial_sidebar_state="collapsed")
9
+
10
+ # --- Helper Functions ---
11
+ def initialize_session_state():
12
+ """Initializes session state variables."""
13
+ if "user_name" not in st.session_state: st.session_state.user_name = ""
14
+ if "user_email" not in st.session_state: st.session_state.user_email = ""
15
+ if "logged_in" not in st.session_state: st.session_state.logged_in = False
16
+ if "llm" not in st.session_state:
17
+ try:
18
+ st.session_state.llm = llm_handler.get_llm()
19
+ except ValueError as e:
20
+ st.error(f"LLM Initialization Error: {e}. Please ensure GOOGLE_API_KEY is set in .env")
21
+ st.stop()
22
+
23
+ if "last_interacted_task_details" not in st.session_state:
24
+ st.session_state.last_interacted_task_details = None
25
+ if "chat_history_for_context" not in st.session_state:
26
+ st.session_state.chat_history_for_context = []
27
+
28
+ # --- Initialize ---
29
+ initialize_session_state()
30
+ db.create_db_and_table()
31
+ if "table_info" not in st.session_state or st.session_state.get("reload_table_info", False):
32
+ st.session_state.table_info = db.get_db_info()
33
+ st.session_state.reload_table_info = False
34
+
35
+
36
+ # --- UI Sections ---
37
+
38
+ if not st.session_state.logged_in:
39
+ st.title("AI Task Manager Login")
40
+ with st.form("login_form"):
41
+ name = st.text_input("Your Name", value=st.session_state.get("user_name_input", ""))
42
+ email = st.text_input("Your Email", value=st.session_state.get("user_email_input", ""))
43
+ login_button = st.form_submit_button("Login")
44
+
45
+ if login_button:
46
+ error_messages = []
47
+ if not name:
48
+ error_messages.append("Please enter your name.")
49
+ if not email:
50
+ error_messages.append("Please enter your email.")
51
+ elif not email.strip().lower().endswith(".com"):
52
+ error_messages.append("Invalid email format.")
53
+
54
+ if not error_messages:
55
+ st.session_state.user_name = name
56
+ st.session_state.user_email = email
57
+ st.session_state.logged_in = True
58
+ st.session_state.user_name_input = name
59
+ st.session_state.user_email_input = email
60
+ st.session_state.last_interacted_task_details = None
61
+ st.session_state.reload_table_info = True
62
+ st.rerun()
63
+ else:
64
+ for msg in error_messages:
65
+ st.error(msg)
66
+ else:
67
+ st.sidebar.header("User Info")
68
+ st.sidebar.write(f"πŸ‘€ **Name:** {st.session_state.user_name}")
69
+ st.sidebar.write(f"πŸ“§ **Email:** {st.session_state.user_email}")
70
+ if st.sidebar.button("Logout"):
71
+ st.session_state.logged_in = False
72
+ st.session_state.user_name = ""
73
+ st.session_state.user_email = ""
74
+ st.session_state.last_interacted_task_details = None
75
+ st.rerun()
76
+
77
+ st.title(f"πŸ“ AI Task Manager for {st.session_state.user_name}")
78
+ st.markdown("Enter your task command (e.g., 'I have a meeting at 2pm on next Friday' , 'Show pending tasks').")
79
+
80
+ if st.session_state.last_interacted_task_details:
81
+ task_ctx = st.session_state.last_interacted_task_details
82
+
83
+ # Prepare task context display message
84
+ task_name = task_ctx.get('task_name', 'N/A')
85
+ task_id = task_ctx.get('id', 'N/A')
86
+ due_date = task_ctx.get('due_date', '')
87
+ due_time = task_ctx.get('due_time', '')
88
+ ctx_display = f"Last task: '{task_name}' (ID: {task_id})"
89
+ if due_date:
90
+ ctx_display += f" - Due: {due_date}"
91
+ if due_time:
92
+ ctx_display += f" at {due_time}"
93
+ st.caption(ctx_display)
94
+
95
+
96
+ user_input_query = st.text_input("Your command:", key="task_input", placeholder="e.g., Add task 'Submit report' due next Friday 3pm category Work")
97
+
98
+ if st.button("Process Command", type="primary"):
99
+ if not user_input_query:
100
+ st.warning("Please enter a command.")
101
+ else:
102
+ llm = st.session_state.llm
103
+ table_info = st.session_state.table_info
104
+
105
+ context_str = "None"
106
+ if st.session_state.last_interacted_task_details:
107
+ details = st.session_state.last_interacted_task_details
108
+ context_list = []
109
+ if details.get('id'): context_list.append(f"id: {details['id']}")
110
+ if details.get('task_name'): context_list.append(f"name: '{details['task_name']}'")
111
+ if details.get('due_date'): context_list.append(f"due_date: {details['due_date']}")
112
+ if details.get('due_time'): context_list.append(f"due_time: {details['due_time']}")
113
+ context_str = f"Task context - {', '.join(context_list)}"
114
+
115
+
116
+ with st.spinner("πŸ€– Thinking and generating SQL..."):
117
+ try:
118
+ generated_sql = llm_handler.generate_sql_query(
119
+ llm,
120
+ user_input_query,
121
+ table_info,
122
+ st.session_state.user_name,
123
+ st.session_state.user_email,
124
+ context_str
125
+ )
126
+ except Exception as e:
127
+ st.error(f"Error generating SQL: {e}")
128
+ generated_sql = None
129
+
130
+ if generated_sql:
131
+ st.write("βš™οΈ **Generated SQL Query:**")
132
+ st.code(generated_sql, language="sql")
133
+
134
+ is_select_query = generated_sql.strip().upper().startswith("SELECT")
135
+ is_insert_query = generated_sql.strip().upper().startswith("INSERT")
136
+
137
+ with st.spinner("πŸ’Ύ Executing query..."):
138
+ try:
139
+ summary_context_for_llm = ""
140
+ if is_select_query:
141
+ data, columns = db.execute_select_query(generated_sql)
142
+ if data:
143
+ df = pd.DataFrame(data, columns=columns)
144
+ major_display_columns = ['id', 'task_name', 'status', 'category', 'due_date', 'due_time', 'created_at']
145
+ display_cols_in_df = [col for col in major_display_columns if col in df.columns]
146
+
147
+ if not display_cols_in_df and df.columns.any():
148
+ display_cols_in_df = df.columns.tolist()
149
+
150
+ if display_cols_in_df:
151
+ st.dataframe(df[display_cols_in_df], use_container_width=True)
152
+ else:
153
+ st.info("The query ran but returned no columns to display.")
154
+
155
+ summary_context_for_llm = f"Retrieved {len(data)} task(s)."
156
+ if len(data) == 1:
157
+ st.session_state.last_interacted_task_details = dict(zip(columns, data[0]))
158
+ elif len(data) == 0:
159
+ summary_context_for_llm = "No tasks found matching your criteria."
160
+ else:
161
+ st.info("No tasks found matching your criteria.")
162
+ summary_context_for_llm = "No tasks found matching your criteria."
163
+ st.session_state.last_interacted_task_details = None
164
+
165
+ else:
166
+ result = db.execute_dml_query(generated_sql)
167
+
168
+ action = "processed"
169
+ if is_insert_query:
170
+ action = "added"
171
+ if result:
172
+ inserted_task_details = db.get_task_by_id(result, st.session_state.user_email)
173
+ if inserted_task_details:
174
+ st.session_state.last_interacted_task_details = inserted_task_details
175
+ summary_context_for_llm = f"Task '{inserted_task_details.get('task_name')}' (ID: {result}) was {action}."
176
+ else:
177
+ summary_context_for_llm = f"Task was {action}, but details couldn't be retrieved post-insertion."
178
+ else:
179
+ summary_context_for_llm = f"Task addition was attempted but may not have completed as expected (no ID returned)."
180
+ elif "UPDATE" in generated_sql.upper():
181
+ action = "updated"
182
+ summary_context_for_llm = f"Task(s) {action}. {result} row(s) affected."
183
+ elif "DELETE" in generated_sql.upper():
184
+ action = "deleted"
185
+ summary_context_for_llm = f"Task(s) {action}. {result} row(s) affected."
186
+ st.session_state.last_interacted_task_details = None
187
+
188
+ st.success(f"Task command '{action}' processed successfully.")
189
+
190
+
191
+ with st.spinner("πŸ“œ Generating friendly summary..."):
192
+ final_summary = llm_handler.summarize_query_result(
193
+ llm,
194
+ user_input_query,
195
+ generated_sql,
196
+ summary_context_for_llm
197
+ )
198
+ st.markdown(f"**πŸ€– Summary:**\n {final_summary}")
199
+
200
+ except ValueError as ve:
201
+ st.error(f"⚠️ Action failed: {ve}")
202
+ except sqlite3.Error as e:
203
+ st.error(f"❌ Database Error: {e}")
204
+ st.error(f" Failed Query: {generated_sql}")
205
+ except Exception as e:
206
+ st.error(f"❌ An unexpected error occurred: {e}")
207
+ st.error(f" Query attempted: {generated_sql}")
208
+
209
+ elif not user_input_query.strip() == "":
210
+ st.error("Could not generate an SQL query for your request. Please try rephrasing.")
211
+
212
+ st.markdown("---")
213
+ st.markdown("Example commands:")
214
+ st.caption("""
215
+ - Add: "Schedule a 'Team sync meeting' for next Tuesday at 10:00 category Work"
216
+ - Add: "I have a 'Doctor's appointment' tomorrow at 3:30 PM"
217
+ - View: "Show my tasks for this week", "What's pending?"
218
+ - Update: "Mark 'Team sync meeting' as completed" (if it was the last task discussed)
219
+ - Update: "I've finished the 'Doctor's appointment'"
220
+ - Delete: "Cancel the 'Team sync meeting'"
221
+ - Delete: "Remove task 'Old project idea'"
 
222
  """)