NavyaNayer commited on
Commit
a7a393e
Β·
verified Β·
1 Parent(s): 34a6d2d

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +402 -494
src/streamlit_app.py CHANGED
@@ -3,14 +3,10 @@ import torch
3
  import os
4
  from dotenv import load_dotenv
5
  from together import Together
6
- from transformers import AutoTokenizer, AutoModelForSequenceClassification, BertTokenizer,DistilBertTokenizer, BertForSequenceClassification, DistilBertForSequenceClassification
7
  from datetime import datetime, timedelta
8
  import pandas as pd
9
  from task_css import get_custom_css # Import the custom CSS function
10
- import gdown
11
-
12
- # Set environment variable for offline mode
13
- os.environ["TRANSFORMERS_OFFLINE"] = "1"
14
 
15
  # Load environment variables
16
  load_dotenv()
@@ -23,536 +19,448 @@ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
23
 
24
  # Load Intent Model
25
  intent_model_path = "intent_classifier.pth"
26
- # Extract file ID from Google Drive URL
27
- file_id = "1_GDGvV3MVvBguIsjMyDLg3RxUV_gnFAY"
28
- num_intent_labels = 151 # Moved this up before model creation
 
 
29
 
30
  # Load Emotion Model
31
  emotions_model_path = "./saved_model"
32
- emotions_folder_id = "1gYWkbC_XBw_GZjsfwXvubHFil4BCq_gH"
33
-
34
- # Add new pretrained model ID
35
- pretrained_folder_id = "13t_EB2LFhRIwb3dkKDtA0O5NXXZBoG-j"
36
-
37
- # Initialize Session State
38
- if "is_ready" not in st.session_state:
39
- st.session_state.is_ready = False
40
- st.session_state.models = {} # Initialize models dict immediately
41
- st.session_state.tasks = []
42
- st.session_state.task_counter = 0
43
- st.session_state.overall_emotion = None
44
- st.session_state.overall_emotion_label = "Neutral"
45
-
46
- # Page Configuration first
47
- st.set_page_config(
48
- page_title="πŸš€ AI Productivity Assistant",
49
- layout="wide",
50
- page_icon="🎯"
51
- )
52
-
53
- # Custom CSS for enhanced styling
54
- st.markdown(get_custom_css(), unsafe_allow_html=True)
55
-
56
- # Show loading screen if models aren't ready
57
- if not st.session_state.is_ready:
58
- st.markdown(
59
- """
60
- <div class="loading-container" style="text-align: center; padding: 50px;">
61
- <div class="loading-spinner"></div>
62
- <h2>Setting up your AI assistant...</h2>
63
- <p>This may take a minute. We're downloading the required models.</p>
64
- </div>
65
- """,
66
- unsafe_allow_html=True
67
- )
68
 
69
- # Load models here
70
- try:
71
- # First download pretrained models
72
- if not os.path.exists("pretrained_models"):
73
- with st.status("Downloading base models...", expanded=True) as status:
74
- os.makedirs("pretrained_models", exist_ok=True)
75
- gdown.download_folder(
76
- f"https://drive.google.com/drive/folders/{pretrained_folder_id}",
77
- output="pretrained_models",
78
- quiet=False
79
- )
80
- status.update(label="Base models downloaded!", state="complete")
81
-
82
- # Intent Model Loading
83
- if not os.path.exists(intent_model_path):
84
- with st.status("Downloading intent model...", expanded=True) as status:
85
- output = gdown.download(
86
- f"https://drive.google.com/uc?id={file_id}",
87
- intent_model_path,
88
- quiet=False
89
- )
90
- status.update(label="Intent model downloaded!", state="complete")
91
-
92
- # Emotion Model Loading
93
- if not os.path.exists(emotions_model_path):
94
- with st.status("Downloading emotion model...", expanded=True) as status:
95
- os.makedirs(emotions_model_path, exist_ok=True)
96
- gdown.download_folder(
97
- f"https://drive.google.com/drive/folders/{emotions_folder_id}",
98
- output=emotions_model_path,
99
- quiet=False
100
- )
101
- status.update(label="Emotion model downloaded!", state="complete")
102
-
103
- # Load and store intent model
104
- intent_model = AutoModelForSequenceClassification.from_pretrained(
105
- "pretrained_models/bert-base-uncased",
106
- num_labels=num_intent_labels,
107
- ignore_mismatched_sizes=True, # Add this parameter
108
- local_files_only=True
109
- )
110
- intent_model.load_state_dict(
111
- torch.load(intent_model_path, map_location=device, weights_only=True)
112
- )
113
- st.session_state.models["intent_model"] = intent_model.to(device).eval()
114
- st.session_state.models["intent_tokenizer"] = AutoTokenizer.from_pretrained(
115
- "pretrained_models/bert-base-uncased",
116
- local_files_only=True
117
- )
118
-
119
- # Load and store emotion model
120
- emotions_model = AutoModelForSequenceClassification.from_pretrained(
121
- emotions_model_path,
122
- ignore_mismatched_sizes=True, # Add this parameter
123
- local_files_only=True
124
- )
125
- st.session_state.models["emotions_model"] = emotions_model.to(device).eval()
126
- st.session_state.models["emotions_tokenizer"] = AutoTokenizer.from_pretrained(
127
- emotions_model_path,
128
- local_files_only=True
129
- )
130
-
131
- # Set ready state
132
- st.session_state.is_ready = True
133
- st.rerun()
134
-
135
- except Exception as e:
136
- st.error(f"Error loading models: {str(e)}")
137
- st.stop()
138
-
139
- # Only show main app if models are ready
140
- if st.session_state.is_ready:
141
- # Title with custom styling
142
- st.markdown('<div class="main-header">🎯 MoodifyTask: AI Task Prioritization & Wellness Assistant</div>', unsafe_allow_html=True)
143
-
144
- # Emotion Labels
145
- emotion_label_names = [
146
- "admiration", "amusement", "anger", "annoyance", "approval",
147
- "caring", "confusion", "curiosity", "desire", "disappointment",
148
- "disapproval", "disgust", "embarrassment", "excitement", "fear",
149
- "gratitude", "grief", "joy", "love", "nervousness",
150
- "optimism", "pride", "realization", "relief", "remorse",
151
- "sadness", "surprise", "neutral"
152
- ]
153
-
154
- # Emotion Categories
155
- positive_emotions = ["admiration", "amusement", "approval", "caring", "curiosity", "excitement", "gratitude", "joy", "love", "optimism", "pride", "relief", "surprise"]
156
- negative_emotions = ["anger", "annoyance", "disappointment", "disapproval", "disgust", "embarrassment", "fear", "grief", "nervousness", "remorse", "sadness"]
157
- neutral_emotions = ["realization", "neutral"]
158
-
159
- # Predict Intent
160
- def predict_intent(sentence):
161
- inputs = st.session_state.models["intent_tokenizer"](
162
- sentence, return_tensors="pt", padding="max_length", truncation=True, max_length=128
163
- )
164
- inputs = {key: val.to(device) for key, val in inputs.items()}
165
- with torch.no_grad():
166
- outputs = st.session_state.models["intent_model"](**inputs)
167
- predicted_class = torch.argmax(outputs.logits, dim=1).cpu().numpy()[0]
168
-
169
- # Mapping Intent IDs to Priorities (0-150)
170
- PRIORITY_MAPPING = {
171
- 5: [8, 35, 42, 74, 97, 110, 118, 120, 124, 136], # freeze_account, report_lost_card, flight_status, report_fraud, credit_limit, lost_luggage, dispute_charge, overdraft, cancel_reservation, emergency
172
- 4: [14, 15, 19, 20, 39, 47, 48, 49, 50, 69, 70, 71, 72], # bill_balance, bill_due, exchange_rate, credit_score, interest_rate, insurance, medical_expenses, appointment_schedule, meeting_schedule, dentist_appointment, doctor_appointment, prescription_refill, pharmacy_hours
173
- 3: [33, 34, 41, 51, 56, 57, 62, 66, 77, 78, 85], # hotel_reservation, car_rental, restaurant_reservation, tracking_package, check_in, check_out, traffic_update, directions, smart_home_on, smart_home_off, weather_forecast
174
- 2: [0, 1, 3, 6, 9, 13, 16, 17, 21, 25, 27, 28, 36, 40, 45, 52, 61], # restaurant_reviews, shopping_list, what_song, schedule_meeting, translate, play_music, book_hotel, book_flight, gas_prices, exchange_rate, movie_showtimes, recipe, cancel_flight, book_reservation, order_food, car_services, joke
175
- 1: [2, 4, 5, 7, 10, 11, 12, 18, 22, 23, 24, 26, 30, 31, 32, 37, 38, 43, 44, 46, 53, 54, 55, 58, 59, 60, 63, 64, 65, 67, 68, 73]
176
- # tell_joke, fun_fact, trivia, horoscope, dog_fact, cat_fact, define_word, stock_price, sports_update, lottery_results, currency_conversion, holiday_list, language_learning, random_fact, poem, quote, daily_horoscope, joke_request, music_recommendation, podcast_recommendation, celebrity_gossip, movie_recommendation, TV_show_recommendation, book_recommendation, game_recommendation, radio_recommendation, trivia_game, riddle, name_meaning, birthday_reminder, anniversary_reminder, affirmations
177
- }
178
-
179
- # Find the priority based on predicted_class
180
- predicted_intent_score = next((priority for priority, ids in PRIORITY_MAPPING.items() if predicted_class in ids), 1) # Default to 1 if not found
181
-
182
- return predicted_intent_score
183
-
184
- # Emotion to Numeric Score Mapping
185
- EMOTION_MAPPING = {
186
- "admiration": 4, "amusement": 3, "anger": 5, "annoyance": 4, "approval": 3,
187
- "caring": 4, "confusion": 3, "curiosity": 3, "desire": 4, "disappointment": 4,
188
- "disapproval": 4, "disgust": 5, "embarrassment": 4, "excitement": 5, "fear": 5,
189
- "gratitude": 3, "grief": 5, "joy": 5, "love": 5, "nervousness": 4,
190
- "optimism": 4, "pride": 4, "realization": 3, "relief": 3, "remorse": 4,
191
- "sadness": 5, "surprise": 3, "neutral": 3
192
  }
193
 
194
- # Function to get numeric emotion score
195
- def get_emotion_score(emotion):
196
- return EMOTION_MAPPING.get(emotion.lower(), 3) # Default to 3 if not found
197
- # Predict Emotion
198
- def predict_emotion(sentence):
199
- if not sentence.strip():
200
- return 3, "neutral"
201
- # Ensure the input is a full sentence
202
- if len(sentence.split()) == 1:
203
- sentence = f"I feel {sentence}"
204
- inputs = st.session_state.models["emotions_tokenizer"](
205
- sentence, return_tensors="pt", padding="max_length", truncation=True, max_length=128
206
- )
207
- inputs = {key: val.to(device) for key, val in inputs.items() if key != "token_type_ids"}
208
-
209
- with torch.no_grad():
210
- outputs = st.session_state.models["emotions_model"](**inputs)
211
- predicted_class = torch.argmax(outputs.logits, dim=1).cpu().numpy()[0]
212
-
213
- detected_emotion = emotion_label_names[predicted_class]
214
-
215
- # Manually adjust for stress/pressure-related words
216
- stress_keywords = ["stress", "stressed", "overwhelmed", "pressure", "tense", "burnout"]
217
- if any(word in sentence.lower() for word in stress_keywords):
218
- if detected_emotion not in ["sadness", "nervousness"]:
219
- detected_emotion = "nervousness" # Change to "sadness" if you prefer
220
-
221
- emotion_score = get_emotion_score(detected_emotion)
222
- if emotion_score is None:
223
- emotion_score = 3 # Default neutral score
224
-
225
- return emotion_score, detected_emotion
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
227
 
228
- # Get Emotion Category
229
- def get_emotion_category(emotion):
230
- if emotion in positive_emotions:
231
- return "positive"
232
- elif emotion in negative_emotions:
233
- return "negative"
234
- else:
235
- return "neutral"
236
 
237
-
238
- def normalize_priority(priority, min_value=0, max_value=10):
239
- return (priority - min_value) / (max_value - min_value) # Normalize between 0-1
240
-
241
- # Calculate Task Priority
242
- def calculate_priority_score(predicted_intent_score,emotion_score, emotion, time_remaining, complexity, emotion_category):
243
- """
244
- Calculate an adaptive priority score for tasks based on intent, emotion, time urgency, and complexity.
245
- """
246
- emotion_score = emotion_score if emotion_score is not None else 3
247
- # Normalize time urgency (scale 0 to 1 based on 7 days)
248
- time_score = max(0, min(1, 1 - (time_remaining.total_seconds() / (7 * 24 * 3600))))
249
-
250
- # Set emotion-based adjustments
251
- stress_emotions = ["nervousness", "sadness", "fear"]
252
- frustration_emotions = ["anger", "frustration","disappointment","annoyance"]
253
- anxiety_emotions = ["anxiety", "uncertainty"]
254
 
 
 
 
 
 
 
 
255
 
256
- if emotion_category == "negative":
257
- if emotion in stress_emotions:
258
- # Prioritize **easy, quick** tasks to reduce cognitive load
259
- priority = (predicted_intent_score * 0.15) + (emotion_score * 0.1) + (time_score * 0.3) + ((10 - complexity) * 0.45)
260
-
261
- elif emotion in frustration_emotions:
262
- # Prioritize **engaging** tasks (not too easy) but keep urgency in mind
263
- priority = (predicted_intent_score * 0.2) + (emotion_score * 0.15) + (time_score * 0.25) + (complexity * 0.4)
264
-
265
- elif emotion in anxiety_emotions:
266
- # Prioritize **urgent, low-complexity** tasks
267
- priority = (predicted_intent_score * 0.2) + (emotion_score * 0.1) + (time_score * 0.4) + ((10 - complexity) * 0.3)
268
-
269
- else:
270
- # Default for negative emotions: balance urgency and ease
271
- priority = (predicted_intent_score * 0.2) + (emotion_score * 0.1) + (time_score * 0.3) + ((10 - complexity) * 0.4)
272
-
273
- elif emotion_category == "positive":
274
- # If the user is in a **good mood**, favor challenging, high-impact tasks
275
- priority = (predicted_intent_score * 0.35) + (emotion_score * 0.2) + (time_score * 0.25) + (complexity * 0.2)
276
 
277
- else: # Neutral emotion
278
- # Keep a balance between difficulty and urgency
279
- priority = (predicted_intent_score * 0.3) + (emotion_score * 0.2) + (time_score * 0.2) + (complexity * 0.3)
280
 
281
- return normalize_priority(priority) # Ensure no negative priority values
282
 
283
 
284
 
285
 
286
- # AI-Generated Plan Based on Start Time
287
- from datetime import datetime
288
 
289
- def get_llama_suggestion(emotion, tasks, selected_datetime):
290
- """Generate AI plan based on full datetime instead of just time"""
291
- # Sort tasks by priority (higher priority first)
292
- sorted_tasks = sorted(tasks, key=lambda x: x["priority_score"], reverse=True)
293
 
294
- # Filter tasks based on selected datetime
295
- filtered_tasks = [
296
- task for task in sorted_tasks
297
- if task["due_date_time"] >= selected_datetime
298
- ]
299
 
300
- if not filtered_tasks:
301
- well_being_prompts = {
302
- "nervousness": "Suggest mindfulness exercises and short relaxation techniques.",
303
- "sadness": "Suggest comforting activities like journaling or light exercise.",
304
- "anger": "Suggest ways to channel frustration productively.",
305
- "joy": "Suggest ways to maintain productivity while feeling good.",
306
- "neutral": "Suggest general relaxation activities like listening to music."
307
- }
308
- well_being_prompt = f"""
309
- The user is feeling {emotion}.
310
- They have no tasks scheduled after {selected_datetime.strftime('%B %d, %I:%M %p')}.
311
- {well_being_prompts.get(emotion, 'Provide general well-being tips.')}
312
- """
313
- try:
314
- response = client.chat.completions.create(
315
- messages=[{"role": "user", "content": well_being_prompt}],
316
- model="meta-llama/Llama-3.3-70B-Instruct-Turbo",
317
- temperature=0.7,
318
- )
319
- return response.choices[0].message.content
320
- except Exception as e:
321
- return f"Error generating well-being tips: {e}"
322
-
323
- # Prepare the prompt with more detailed datetime information
324
- task_details = "\n".join([
325
- f"- {task['description']} (Priority: {task['priority_score']:.2f}, Complexity: {task['complexity']}, Due: {task['due_date_time'].strftime('%B %d, %I:%M %p')})"
326
- for task in filtered_tasks
327
- ])
328
-
329
- prompt = f"""
330
- The user is feeling {emotion}.
331
- They need a structured productivity plan starting from {selected_datetime.strftime('%B %d, %I:%M %p')}, not the current time.
332
-
333
- Their prioritized tasks (due on or after the selected time), sorted by priority score:
334
- {task_details}
335
-
336
- Please provide:
337
- 1. A detailed schedule with specific times for each task
338
- 2. Strategic breaks based on task complexity and emotional state
339
- 3. Wellness activities that complement their current emotion
340
- 4. Tips for managing tasks effectively given their emotional state
341
- 5. Suggestions for handling high-priority tasks first while maintaining well-being
342
  """
343
-
344
  try:
345
  response = client.chat.completions.create(
346
- messages=[{"role": "user", "content": prompt}],
347
  model="meta-llama/Llama-3.3-70B-Instruct-Turbo",
348
  temperature=0.7,
349
  )
350
  return response.choices[0].message.content
351
  except Exception as e:
352
- return f"Error generating AI plan: {e}"
353
 
 
 
 
 
 
354
 
355
- # Layout with improved spacing
356
- col1, col2 = st.columns([1, 1], gap="medium")
 
 
 
 
357
 
358
- with col1:
359
- # st.markdown('<div class="emotion-analysis">', unsafe_allow_html=True)
360
- st.markdown('<h3>🌟 Mood Analysis</h3>', unsafe_allow_html=True)
361
- emotion_sentence = st.text_area(
362
- "Describe how you're feeling today:",
363
- value="",
364
- height=150,
365
- help="Your emotional state helps us prioritize tasks more effectively"
 
 
 
 
 
366
  )
 
 
 
367
 
368
- if emotion_sentence:
369
- emotion_score, emotion_label = predict_emotion(emotion_sentence)
370
- st.session_state.overall_emotion = emotion_score
371
- st.session_state.overall_emotion_label = emotion_label
372
-
373
- st.markdown(f'<div class="emotion-badge">Detected Emotion: {emotion_label}</div>', unsafe_allow_html=True)
374
-
375
- # Emotion-based task reprioritization
376
- for task in st.session_state.tasks:
377
- task["priority_score"] = calculate_priority_score(
378
- task["predicted_intent_score"],
379
- emotion_score,
380
- emotion_label,
381
- task["time_remaining"],
382
- task["complexity"],
383
- get_emotion_category(emotion_label)
384
- )
385
- st.markdown('</div>', unsafe_allow_html=True)
386
 
387
- with col2:
388
- # st.markdown('<div class="task-input">', unsafe_allow_html=True)
389
- st.markdown('<h3>πŸ“… Add New Task</h3>', unsafe_allow_html=True)
390
- with st.form("task_form", clear_on_submit=True):
391
- task_description = st.text_input("Task Description", help="Be specific about what needs to be done")
392
- col_date, col_time = st.columns(2)
393
-
394
- with col_date:
395
- due_date = st.date_input("Due Date")
396
-
397
- with col_time:
398
- due_time = st.time_input("Due Time")
399
-
400
- complexity = st.slider(
401
- "Task Complexity (1-10)",
402
- 1, 10, 5,
403
- help="Higher complexity may affect task priority"
404
- )
405
-
406
- submitted = st.form_submit_button("βž• Add Task")
407
-
408
- if submitted and task_description and due_date and due_time:
409
- due_date_time = datetime.combine(due_date, due_time)
410
- time_remaining = due_date_time - datetime.now()
411
- predicted_intent_score = predict_intent(task_description)
412
-
413
- task = {
414
- "id": st.session_state.task_counter, # Add unique ID
415
- "description": task_description,
416
- "due_date_time": due_date_time,
417
- "time_remaining": time_remaining,
418
- "complexity": complexity,
419
- "predicted_intent_score": predicted_intent_score,
420
- "predicted_emotion": st.session_state.overall_emotion,
421
- "predicted_label_name": st.session_state.overall_emotion_label,
422
- "priority_score": calculate_priority_score(
423
- predicted_intent_score,
424
- st.session_state.overall_emotion,
425
- st.session_state.overall_emotion_label,
426
- time_remaining,
427
- complexity,
428
- get_emotion_category(st.session_state.overall_emotion_label)
429
- ),
430
- "completed": False
431
- }
432
-
433
- st.session_state.tasks.append(task)
434
- st.session_state.task_counter += 1 # Increment counter
435
- st.success("βœ… Task Added Successfully!")
436
- st.markdown('</div>', unsafe_allow_html=True)
437
-
438
- # Task List with Improved Visualization
439
- if st.session_state.tasks:
440
- st.markdown('<h3>πŸ“Œ Task Priority List</h3>', unsafe_allow_html=True)
441
-
442
- # Sort tasks by priority
443
- sorted_tasks = sorted(st.session_state.tasks, key=lambda x: x["priority_score"], reverse=True)
444
-
445
- # Create task overview cards
446
- st.markdown('<div class="task-overview">', unsafe_allow_html=True)
447
- col1, col2 = st.columns(2)
448
- with col1:
449
- st.markdown(f'<div class="metric-card"><div class="metric-value">{len(sorted_tasks)}</div><div class="metric-label">Total Tasks</div></div>', unsafe_allow_html=True)
450
- # with col2:
451
- # high_priority = len([t for t in sorted_tasks if t["priority_score"] > 0.7])
452
- # st.markdown(f'<div class="metric-card"><div class="metric-value">{high_priority}</div><div class="metric-label">High Priority</div></div>', unsafe_allow_html=True)
453
- with col2:
454
- today = datetime.now()
455
- due_today = len([t for t in sorted_tasks if t["due_date_time"].date() == today.date()])
456
- st.markdown(f'<div class="metric-card"><div class="metric-value">{due_today}</div><div class="metric-label">Due Today</div></div>', unsafe_allow_html=True)
457
- st.markdown('</div>', unsafe_allow_html=True)
458
 
459
- # Display tasks with priority-based styling
460
- for idx, task in enumerate(sorted_tasks):
461
- priority_class = "high-priority" if task["priority_score"] > 0.7 else "medium-priority"
462
-
463
- # Create a single row for task and buttons
464
- task_container = st.container()
465
- with task_container:
466
- cols = st.columns([0.8, 0.1, 0.1])
467
-
468
- # Task content in first column
469
- with cols[0]:
470
- st.markdown(f"""
471
- <div class="priority-task {priority_class}">
472
- <div class="task-content">
473
- <div class="task-header">
474
- <span class="task-title">{task["description"]}</span>
475
- <span class="priority-score">Priority: {task["priority_score"]:.2f}</span>
476
- </div>
477
- <div class="task-details">
478
- <span class="task-stat">Due: {task["due_date_time"].strftime("%d %b, %I:%M %p")}</span>
479
- <span class="task-stat">Complexity: {task["complexity"]}</span>
480
- </div>
481
- </div>
482
- </div>
483
- """, unsafe_allow_html=True)
484
- st.session_state.editing_task_id = None
485
- # Edit button
486
- with cols[1]:
487
- if st.button("✏️", key=f"edit_{idx}", help="Edit task"):
488
- st.session_state.editing_task_id = idx
489
-
490
- # Delete button
491
- with cols[2]:
492
- if st.button("πŸ—‘οΈ", key=f"delete_{idx}", help="Delete task"):
493
- st.session_state.tasks.pop(idx)
494
- st.success("Task deleted!")
495
- st.rerun()
496
-
497
- # Show edit form below the task if being edited
498
- if st.session_state.editing_task_id == idx:
499
- with st.form(key=f"edit_form_{idx}"):
500
- col1, col2 = st.columns(2)
501
- with col1:
502
- new_description = st.text_input("Description", value=task["description"])
503
- new_complexity = st.slider("Complexity", 1, 10, value=task["complexity"])
504
- with col2:
505
- new_due_date = st.date_input("Due Date", value=task["due_date_time"].date())
506
- new_due_time = st.time_input("Due Time", value=task["due_date_time"].time())
507
-
508
- col1, col2 = st.columns(2)
509
- with col1:
510
- if st.form_submit_button("πŸ’Ύ Save"):
511
- # Update task
512
- task["description"] = new_description
513
- task["due_date_time"] = datetime.combine(new_due_date, new_due_time)
514
- task["time_remaining"] = task["due_date_time"] - datetime.now()
515
- task["complexity"] = new_complexity
516
-
517
- # Recalculate priority
518
- task["priority_score"] = calculate_priority_score(
519
- task["predicted_intent_score"],
520
- task["predicted_emotion"],
521
- task["predicted_label_name"],
522
- task["time_remaining"],
523
- task["complexity"],
524
- get_emotion_category(task["predicted_label_name"])
525
- )
526
- st.session_state.editing_task_id = None
527
- st.success("Task updated!")
528
- st.rerun()
529
-
530
- with col2:
531
- if st.form_submit_button("❌ Cancel"):
532
- st.session_state.editing_task_id = None
533
- st.rerun()
534
-
535
- # AI Plan Section
536
- if st.session_state.tasks:
537
- st.markdown('<div class="custom-card">', unsafe_allow_html=True)
538
- st.markdown('<h3>⏰ AI Task Planning</h3>', unsafe_allow_html=True)
539
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
540
  col_date, col_time = st.columns(2)
541
 
542
  with col_date:
543
- plan_date = st.date_input("Select Plan Date", datetime.now().date())
544
 
545
  with col_time:
546
- plan_time = st.time_input("Select Plan Start Time", datetime.now().time())
 
 
 
 
 
 
 
 
547
 
548
- selected_datetime = datetime.combine(plan_date, plan_time)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
549
 
550
- if st.button("πŸ“… Generate AI Plan"):
551
- suggestion = get_llama_suggestion(
552
- st.session_state.overall_emotion_label,
553
- st.session_state.tasks,
554
- selected_datetime # Pass full datetime object
555
- )
556
- st.markdown(f'<div class="info-box">{suggestion}</div>', unsafe_allow_html=True)
557
- st.markdown('</div>', unsafe_allow_html=True)
558
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  import os
4
  from dotenv import load_dotenv
5
  from together import Together
6
+ from transformers import BertTokenizer,DistilBertTokenizer, BertForSequenceClassification, DistilBertForSequenceClassification
7
  from datetime import datetime, timedelta
8
  import pandas as pd
9
  from task_css import get_custom_css # Import the custom CSS function
 
 
 
 
10
 
11
  # Load environment variables
12
  load_dotenv()
 
19
 
20
  # Load Intent Model
21
  intent_model_path = "intent_classifier.pth"
22
+ num_intent_labels = 151
23
+ intent_model = BertForSequenceClassification.from_pretrained("bert-base-uncased", num_labels=num_intent_labels)
24
+ intent_model.load_state_dict(torch.load(intent_model_path, map_location=device))
25
+ intent_tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
26
+ intent_model.to(device).eval()
27
 
28
  # Load Emotion Model
29
  emotions_model_path = "./saved_model"
30
+ emotions_model = DistilBertForSequenceClassification.from_pretrained(emotions_model_path)
31
+ emotions_tokenizer = DistilBertTokenizer.from_pretrained(emotions_model_path)
32
+ emotions_model.to(device).eval()
33
+
34
+ # Emotion Labels
35
+ emotion_label_names = [
36
+ "admiration", "amusement", "anger", "annoyance", "approval",
37
+ "caring", "confusion", "curiosity", "desire", "disappointment",
38
+ "disapproval", "disgust", "embarrassment", "excitement", "fear",
39
+ "gratitude", "grief", "joy", "love", "nervousness",
40
+ "optimism", "pride", "realization", "relief", "remorse",
41
+ "sadness", "surprise", "neutral"
42
+ ]
43
+
44
+ # Emotion Categories
45
+ positive_emotions = ["admiration", "amusement", "approval", "caring", "curiosity", "excitement", "gratitude", "joy", "love", "optimism", "pride", "relief", "surprise"]
46
+ negative_emotions = ["anger", "annoyance", "disappointment", "disapproval", "disgust", "embarrassment", "fear", "grief", "nervousness", "remorse", "sadness"]
47
+ neutral_emotions = ["realization", "neutral"]
48
+
49
+ # Predict Intent
50
+ def predict_intent(sentence):
51
+ inputs = intent_tokenizer(sentence, return_tensors="pt", padding="max_length", truncation=True, max_length=128)
52
+ inputs = {key: val.to(device) for key, val in inputs.items()}
53
+ with torch.no_grad():
54
+ outputs = intent_model(**inputs)
55
+ predicted_class = torch.argmax(outputs.logits, dim=1).cpu().numpy()[0]
 
 
 
 
 
 
 
 
 
 
56
 
57
+ # Mapping Intent IDs to Priorities (0-150)
58
+ PRIORITY_MAPPING = {
59
+ 5: [8, 35, 42, 74, 97, 110, 118, 120, 124, 136], # freeze_account, report_lost_card, flight_status, report_fraud, credit_limit, lost_luggage, dispute_charge, overdraft, cancel_reservation, emergency
60
+ 4: [14, 15, 19, 20, 39, 47, 48, 49, 50, 69, 70, 71, 72], # bill_balance, bill_due, exchange_rate, credit_score, interest_rate, insurance, medical_expenses, appointment_schedule, meeting_schedule, dentist_appointment, doctor_appointment, prescription_refill, pharmacy_hours
61
+ 3: [33, 34, 41, 51, 56, 57, 62, 66, 77, 78, 85], # hotel_reservation, car_rental, restaurant_reservation, tracking_package, check_in, check_out, traffic_update, directions, smart_home_on, smart_home_off, weather_forecast
62
+ 2: [0, 1, 3, 6, 9, 13, 16, 17, 21, 25, 27, 28, 36, 40, 45, 52, 61], # restaurant_reviews, shopping_list, what_song, schedule_meeting, translate, play_music, book_hotel, book_flight, gas_prices, exchange_rate, movie_showtimes, recipe, cancel_flight, book_reservation, order_food, car_services, joke
63
+ 1: [2, 4, 5, 7, 10, 11, 12, 18, 22, 23, 24, 26, 30, 31, 32, 37, 38, 43, 44, 46, 53, 54, 55, 58, 59, 60, 63, 64, 65, 67, 68, 73]
64
+ # tell_joke, fun_fact, trivia, horoscope, dog_fact, cat_fact, define_word, stock_price, sports_update, lottery_results, currency_conversion, holiday_list, language_learning, random_fact, poem, quote, daily_horoscope, joke_request, music_recommendation, podcast_recommendation, celebrity_gossip, movie_recommendation, TV_show_recommendation, book_recommendation, game_recommendation, radio_recommendation, trivia_game, riddle, name_meaning, birthday_reminder, anniversary_reminder, affirmations
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  }
66
 
67
+ # Find the priority based on predicted_class
68
+ predicted_intent_score = next((priority for priority, ids in PRIORITY_MAPPING.items() if predicted_class in ids), 1) # Default to 1 if not found
69
+
70
+ return predicted_intent_score
71
+
72
+ # Emotion to Numeric Score Mapping
73
+ EMOTION_MAPPING = {
74
+ "admiration": 4, "amusement": 3, "anger": 5, "annoyance": 4, "approval": 3,
75
+ "caring": 4, "confusion": 3, "curiosity": 3, "desire": 4, "disappointment": 4,
76
+ "disapproval": 4, "disgust": 5, "embarrassment": 4, "excitement": 5, "fear": 5,
77
+ "gratitude": 3, "grief": 5, "joy": 5, "love": 5, "nervousness": 4,
78
+ "optimism": 4, "pride": 4, "realization": 3, "relief": 3, "remorse": 4,
79
+ "sadness": 5, "surprise": 3, "neutral": 3
80
+ }
81
+
82
+ # Function to get numeric emotion score
83
+ def get_emotion_score(emotion):
84
+ return EMOTION_MAPPING.get(emotion.lower(), 3) # Default to 3 if not found
85
+ # Predict Emotion
86
+ def predict_emotion(sentence):
87
+ if not sentence.strip():
88
+ return 3, "neutral"
89
+ # Ensure the input is a full sentence
90
+ if len(sentence.split()) == 1:
91
+ sentence = f"I feel {sentence}"
92
+ inputs = emotions_tokenizer(sentence, return_tensors="pt", padding="max_length", truncation=True, max_length=128)
93
+ inputs = {key: val.to(device) for key, val in inputs.items() if key != "token_type_ids"}
94
+
95
+ with torch.no_grad():
96
+ outputs = emotions_model(**inputs)
97
+ predicted_class = torch.argmax(outputs.logits, dim=1).cpu().numpy()[0]
98
+
99
+ detected_emotion = emotion_label_names[predicted_class]
100
+
101
+ # Manually adjust for stress/pressure-related words
102
+ stress_keywords = ["stress", "stressed", "overwhelmed", "pressure", "tense", "burnout"]
103
+ if any(word in sentence.lower() for word in stress_keywords):
104
+ if detected_emotion not in ["sadness", "nervousness"]:
105
+ detected_emotion = "nervousness" # Change to "sadness" if you prefer
106
+
107
+ emotion_score = get_emotion_score(detected_emotion)
108
+ if emotion_score is None:
109
+ emotion_score = 3 # Default neutral score
110
+
111
+ return emotion_score, detected_emotion
112
+
113
+
114
+ # Get Emotion Category
115
+ def get_emotion_category(emotion):
116
+ if emotion in positive_emotions:
117
+ return "positive"
118
+ elif emotion in negative_emotions:
119
+ return "negative"
120
+ else:
121
+ return "neutral"
122
+
123
 
124
+ def normalize_priority(priority, min_value=0, max_value=10):
125
+ return (priority - min_value) / (max_value - min_value) # Normalize between 0-1
126
+
127
+ # Calculate Task Priority
128
+ def calculate_priority_score(predicted_intent_score,emotion_score, emotion, time_remaining, complexity, emotion_category):
129
+ """
130
+ Calculate an adaptive priority score for tasks based on intent, emotion, time urgency, and complexity.
131
+ """
132
+ emotion_score = emotion_score if emotion_score is not None else 3
133
+ # Normalize time urgency (scale 0 to 1 based on 7 days)
134
+ time_score = max(0, min(1, 1 - (time_remaining.total_seconds() / (7 * 24 * 3600))))
135
+
136
+ # Set emotion-based adjustments
137
+ stress_emotions = ["nervousness", "sadness", "fear"]
138
+ frustration_emotions = ["anger", "frustration","disappointment","annoyance"]
139
+ anxiety_emotions = ["anxiety", "uncertainty"]
140
+
141
 
142
+ if emotion_category == "negative":
143
+ if emotion in stress_emotions:
144
+ # Prioritize **easy, quick** tasks to reduce cognitive load
145
+ priority = (predicted_intent_score * 0.15) + (emotion_score * 0.1) + (time_score * 0.3) + ((10 - complexity) * 0.45)
 
 
 
 
146
 
147
+ elif emotion in frustration_emotions:
148
+ # Prioritize **engaging** tasks (not too easy) but keep urgency in mind
149
+ priority = (predicted_intent_score * 0.2) + (emotion_score * 0.15) + (time_score * 0.25) + (complexity * 0.4)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
 
151
+ elif emotion in anxiety_emotions:
152
+ # Prioritize **urgent, low-complexity** tasks
153
+ priority = (predicted_intent_score * 0.2) + (emotion_score * 0.1) + (time_score * 0.4) + ((10 - complexity) * 0.3)
154
+
155
+ else:
156
+ # Default for negative emotions: balance urgency and ease
157
+ priority = (predicted_intent_score * 0.2) + (emotion_score * 0.1) + (time_score * 0.3) + ((10 - complexity) * 0.4)
158
 
159
+ elif emotion_category == "positive":
160
+ # If the user is in a **good mood**, favor challenging, high-impact tasks
161
+ priority = (predicted_intent_score * 0.35) + (emotion_score * 0.2) + (time_score * 0.25) + (complexity * 0.2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162
 
163
+ else: # Neutral emotion
164
+ # Keep a balance between difficulty and urgency
165
+ priority = (predicted_intent_score * 0.3) + (emotion_score * 0.2) + (time_score * 0.2) + (complexity * 0.3)
166
 
167
+ return normalize_priority(priority) # Ensure no negative priority values
168
 
169
 
170
 
171
 
172
+ # AI-Generated Plan Based on Start Time
173
+ from datetime import datetime
174
 
175
+ def get_llama_suggestion(emotion, tasks, selected_datetime):
176
+ """Generate AI plan based on full datetime instead of just time"""
177
+ # Sort tasks by priority (higher priority first)
178
+ sorted_tasks = sorted(tasks, key=lambda x: x["priority_score"], reverse=True)
179
 
180
+ # Filter tasks based on selected datetime
181
+ filtered_tasks = [
182
+ task for task in sorted_tasks
183
+ if task["due_date_time"] >= selected_datetime
184
+ ]
185
 
186
+ if not filtered_tasks:
187
+ well_being_prompts = {
188
+ "nervousness": "Suggest mindfulness exercises and short relaxation techniques.",
189
+ "sadness": "Suggest comforting activities like journaling or light exercise.",
190
+ "anger": "Suggest ways to channel frustration productively.",
191
+ "joy": "Suggest ways to maintain productivity while feeling good.",
192
+ "neutral": "Suggest general relaxation activities like listening to music."
193
+ }
194
+ well_being_prompt = f"""
195
+ The user is feeling {emotion}.
196
+ They have no tasks scheduled after {selected_datetime.strftime('%B %d, %I:%M %p')}.
197
+ {well_being_prompts.get(emotion, 'Provide general well-being tips.')}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
  """
 
199
  try:
200
  response = client.chat.completions.create(
201
+ messages=[{"role": "user", "content": well_being_prompt}],
202
  model="meta-llama/Llama-3.3-70B-Instruct-Turbo",
203
  temperature=0.7,
204
  )
205
  return response.choices[0].message.content
206
  except Exception as e:
207
+ return f"Error generating well-being tips: {e}"
208
 
209
+ # Prepare the prompt with more detailed datetime information
210
+ task_details = "\n".join([
211
+ f"- {task['description']} (Priority: {task['priority_score']:.2f}, Complexity: {task['complexity']}, Due: {task['due_date_time'].strftime('%B %d, %I:%M %p')})"
212
+ for task in filtered_tasks
213
+ ])
214
 
215
+ prompt = f"""
216
+ The user is feeling {emotion}.
217
+ They need a structured productivity plan starting from {selected_datetime.strftime('%B %d, %I:%M %p')}, not the current time.
218
+
219
+ Their prioritized tasks (due on or after the selected time), sorted by priority score:
220
+ {task_details}
221
 
222
+ Please provide:
223
+ 1. A detailed schedule with specific times for each task
224
+ 2. Strategic breaks based on task complexity and emotional state
225
+ 3. Wellness activities that complement their current emotion
226
+ 4. Tips for managing tasks effectively given their emotional state
227
+ 5. Suggestions for handling high-priority tasks first while maintaining well-being
228
+ """
229
+
230
+ try:
231
+ response = client.chat.completions.create(
232
+ messages=[{"role": "user", "content": prompt}],
233
+ model="meta-llama/Llama-3.3-70B-Instruct-Turbo",
234
+ temperature=0.7,
235
  )
236
+ return response.choices[0].message.content
237
+ except Exception as e:
238
+ return f"Error generating AI plan: {e}"
239
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
 
241
+ # Page Configuration
242
+ st.set_page_config(
243
+ page_title="πŸš€ AI Productivity Assistant",
244
+ layout="wide",
245
+ page_icon="🎯"
246
+ )
247
+
248
+ # Custom CSS for enhanced styling
249
+ st.markdown(get_custom_css(), unsafe_allow_html=True)
250
+
251
+ # Title with custom styling
252
+ st.markdown('<div class="main-header">🎯 MoodifyTask: AI Task Prioritization & Wellness Assistant</div>', unsafe_allow_html=True)
253
+
254
+ # Initialize Session State
255
+ if "tasks" not in st.session_state:
256
+ st.session_state.tasks = []
257
+ if "task_counter" not in st.session_state: # Add counter for unique IDs
258
+ st.session_state.task_counter = 0
259
+ if "overall_emotion" not in st.session_state:
260
+ st.session_state.overall_emotion = None
261
+ if "overall_emotion_label" not in st.session_state:
262
+ st.session_state.overall_emotion_label = "Neutral"
263
+
264
+ # Layout with improved spacing
265
+ col1, col2 = st.columns([1, 1], gap="medium")
266
+
267
+ with col1:
268
+ # st.markdown('<div class="emotion-analysis">', unsafe_allow_html=True)
269
+ st.markdown('<h3>🌟 Mood Analysis</h3>', unsafe_allow_html=True)
270
+ emotion_sentence = st.text_area(
271
+ "Describe how you're feeling today:",
272
+ value="",
273
+ height=150,
274
+ help="Your emotional state helps us prioritize tasks more effectively"
275
+ )
276
+
277
+ if emotion_sentence:
278
+ emotion_score, emotion_label = predict_emotion(emotion_sentence)
279
+ st.session_state.overall_emotion = emotion_score
280
+ st.session_state.overall_emotion_label = emotion_label
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281
 
282
+ st.markdown(f'<div class="emotion-badge">Detected Emotion: {emotion_label}</div>', unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
283
 
284
+ # Emotion-based task reprioritization
285
+ for task in st.session_state.tasks:
286
+ task["priority_score"] = calculate_priority_score(
287
+ task["predicted_intent_score"],
288
+ emotion_score,
289
+ emotion_label,
290
+ task["time_remaining"],
291
+ task["complexity"],
292
+ get_emotion_category(emotion_label)
293
+ )
294
+ st.markdown('</div>', unsafe_allow_html=True)
295
+
296
+ with col2:
297
+ # st.markdown('<div class="task-input">', unsafe_allow_html=True)
298
+ st.markdown('<h3>πŸ“… Add New Task</h3>', unsafe_allow_html=True)
299
+ with st.form("task_form", clear_on_submit=True):
300
+ task_description = st.text_input("Task Description", help="Be specific about what needs to be done")
301
  col_date, col_time = st.columns(2)
302
 
303
  with col_date:
304
+ due_date = st.date_input("Due Date")
305
 
306
  with col_time:
307
+ due_time = st.time_input("Due Time")
308
+
309
+ complexity = st.slider(
310
+ "Task Complexity (1-10)",
311
+ 1, 10, 5,
312
+ help="Higher complexity may affect task priority"
313
+ )
314
+
315
+ submitted = st.form_submit_button("βž• Add Task")
316
 
317
+ if submitted and task_description and due_date and due_time:
318
+ due_date_time = datetime.combine(due_date, due_time)
319
+ time_remaining = due_date_time - datetime.now()
320
+ predicted_intent_score = predict_intent(task_description)
321
+
322
+ task = {
323
+ "id": st.session_state.task_counter, # Add unique ID
324
+ "description": task_description,
325
+ "due_date_time": due_date_time,
326
+ "time_remaining": time_remaining,
327
+ "complexity": complexity,
328
+ "predicted_intent_score": predicted_intent_score,
329
+ "predicted_emotion": st.session_state.overall_emotion,
330
+ "predicted_label_name": st.session_state.overall_emotion_label,
331
+ "priority_score": calculate_priority_score(
332
+ predicted_intent_score,
333
+ st.session_state.overall_emotion,
334
+ st.session_state.overall_emotion_label,
335
+ time_remaining,
336
+ complexity,
337
+ get_emotion_category(st.session_state.overall_emotion_label)
338
+ ),
339
+ "completed": False
340
+ }
341
 
342
+ st.session_state.tasks.append(task)
343
+ st.session_state.task_counter += 1 # Increment counter
344
+ st.success("βœ… Task Added Successfully!")
345
+ st.markdown('</div>', unsafe_allow_html=True)
 
 
 
 
346
 
347
+ # Task List with Improved Visualization
348
+ if st.session_state.tasks:
349
+ st.markdown('<h3>πŸ“Œ Task Priority List</h3>', unsafe_allow_html=True)
350
+
351
+ # Sort tasks by priority
352
+ sorted_tasks = sorted(st.session_state.tasks, key=lambda x: x["priority_score"], reverse=True)
353
+
354
+ # Create task overview cards
355
+ st.markdown('<div class="task-overview">', unsafe_allow_html=True)
356
+ col1, col2 = st.columns(2)
357
+ with col1:
358
+ st.markdown(f'<div class="metric-card"><div class="metric-value">{len(sorted_tasks)}</div><div class="metric-label">Total Tasks</div></div>', unsafe_allow_html=True)
359
+ # with col2:
360
+ # high_priority = len([t for t in sorted_tasks if t["priority_score"] > 0.7])
361
+ # st.markdown(f'<div class="metric-card"><div class="metric-value">{high_priority}</div><div class="metric-label">High Priority</div></div>', unsafe_allow_html=True)
362
+ with col2:
363
+ today = datetime.now()
364
+ due_today = len([t for t in sorted_tasks if t["due_date_time"].date() == today.date()])
365
+ st.markdown(f'<div class="metric-card"><div class="metric-value">{due_today}</div><div class="metric-label">Due Today</div></div>', unsafe_allow_html=True)
366
+ st.markdown('</div>', unsafe_allow_html=True)
367
+
368
+ # Display tasks with priority-based styling
369
+ for idx, task in enumerate(sorted_tasks):
370
+ priority_class = "high-priority" if task["priority_score"] > 0.7 else "medium-priority"
371
+
372
+ # Create a single row for task and buttons
373
+ task_container = st.container()
374
+ with task_container:
375
+ cols = st.columns([0.8, 0.1, 0.1])
376
+
377
+ # Task content in first column
378
+ with cols[0]:
379
+ st.markdown(f"""
380
+ <div class="priority-task {priority_class}">
381
+ <div class="task-content">
382
+ <div class="task-header">
383
+ <span class="task-title">{task["description"]}</span>
384
+ <span class="priority-score">Priority: {task["priority_score"]:.2f}</span>
385
+ </div>
386
+ <div class="task-details">
387
+ <span class="task-stat">Due: {task["due_date_time"].strftime("%d %b, %I:%M %p")}</span>
388
+ <span class="task-stat">Complexity: {task["complexity"]}</span>
389
+ </div>
390
+ </div>
391
+ </div>
392
+ """, unsafe_allow_html=True)
393
+ st.session_state.editing_task_id = None
394
+ # Edit button
395
+ with cols[1]:
396
+ if st.button("✏️", key=f"edit_{idx}", help="Edit task"):
397
+ st.session_state.editing_task_id = idx
398
+
399
+ # Delete button
400
+ with cols[2]:
401
+ if st.button("πŸ—‘οΈ", key=f"delete_{idx}", help="Delete task"):
402
+ st.session_state.tasks.pop(idx)
403
+ st.success("Task deleted!")
404
+ st.rerun()
405
+
406
+ # Show edit form below the task if being edited
407
+ if st.session_state.editing_task_id == idx:
408
+ with st.form(key=f"edit_form_{idx}"):
409
+ col1, col2 = st.columns(2)
410
+ with col1:
411
+ new_description = st.text_input("Description", value=task["description"])
412
+ new_complexity = st.slider("Complexity", 1, 10, value=task["complexity"])
413
+ with col2:
414
+ new_due_date = st.date_input("Due Date", value=task["due_date_time"].date())
415
+ new_due_time = st.time_input("Due Time", value=task["due_date_time"].time())
416
+
417
+ col1, col2 = st.columns(2)
418
+ with col1:
419
+ if st.form_submit_button("πŸ’Ύ Save"):
420
+ # Update task
421
+ task["description"] = new_description
422
+ task["due_date_time"] = datetime.combine(new_due_date, new_due_time)
423
+ task["time_remaining"] = task["due_date_time"] - datetime.now()
424
+ task["complexity"] = new_complexity
425
+
426
+ # Recalculate priority
427
+ task["priority_score"] = calculate_priority_score(
428
+ task["predicted_intent_score"],
429
+ task["predicted_emotion"],
430
+ task["predicted_label_name"],
431
+ task["time_remaining"],
432
+ task["complexity"],
433
+ get_emotion_category(task["predicted_label_name"])
434
+ )
435
+ st.session_state.editing_task_id = None
436
+ st.success("Task updated!")
437
+ st.rerun()
438
+
439
+ with col2:
440
+ if st.form_submit_button("❌ Cancel"):
441
+ st.session_state.editing_task_id = None
442
+ st.rerun()
443
+
444
+ # AI Plan Section
445
+ if st.session_state.tasks:
446
+ st.markdown('<div class="custom-card">', unsafe_allow_html=True)
447
+ st.markdown('<h3>⏰ AI Task Planning</h3>', unsafe_allow_html=True)
448
+
449
+ col_date, col_time = st.columns(2)
450
+
451
+ with col_date:
452
+ plan_date = st.date_input("Select Plan Date", datetime.now().date())
453
+
454
+ with col_time:
455
+ plan_time = st.time_input("Select Plan Start Time", datetime.now().time())
456
+
457
+ selected_datetime = datetime.combine(plan_date, plan_time)
458
+
459
+ if st.button("πŸ“… Generate AI Plan"):
460
+ suggestion = get_llama_suggestion(
461
+ st.session_state.overall_emotion_label,
462
+ st.session_state.tasks,
463
+ selected_datetime # Pass full datetime object
464
+ )
465
+ st.markdown(f'<div class="info-box">{suggestion}</div>', unsafe_allow_html=True)
466
+ st.markdown('</div>', unsafe_allow_html=True)