Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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
|
| 5 |
-
import
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
""
|
| 14 |
-
if "
|
| 15 |
-
if "
|
| 16 |
-
if "
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
st.
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
st.session_state.
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
st.
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
st.session_state.
|
| 57 |
-
st.session_state.
|
| 58 |
-
st.session_state.
|
| 59 |
-
st.session_state.
|
| 60 |
-
st.session_state.
|
| 61 |
-
st.session_state.
|
| 62 |
-
st.
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
st.sidebar.
|
| 69 |
-
st.sidebar.write(f"
|
| 70 |
-
st.sidebar.
|
| 71 |
-
|
| 72 |
-
st.session_state.
|
| 73 |
-
st.session_state.
|
| 74 |
-
st.session_state.
|
| 75 |
-
st.
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
st.
|
| 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 |
-
if details.get('
|
| 111 |
-
if details.get('
|
| 112 |
-
if details.get('
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
st.session_state.
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
st.
|
| 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 |
-
st.error(f"
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
st.error(f"
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
st.markdown("
|
| 214 |
-
st.
|
| 215 |
-
|
| 216 |
-
- Add: "
|
| 217 |
-
-
|
| 218 |
-
-
|
| 219 |
-
- Update: "
|
| 220 |
-
-
|
| 221 |
-
- Delete: "
|
| 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 |
""")
|