NavyaNayer commited on
Commit
131b751
Β·
verified Β·
1 Parent(s): 2f5430d

Update src/task.py

Browse files
Files changed (1) hide show
  1. src/task.py +557 -558
src/task.py CHANGED
@@ -1,558 +1,557 @@
1
- import streamlit as st
2
- 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()
17
-
18
- # Together AI Client with API key from environment variable
19
- client = Together(api_key=os.getenv("TOGETHER_API_KEY", ""))
20
-
21
- # Set device
22
- 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
-
 
1
+ import streamlit as st
2
+ 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()
17
+
18
+ # Together AI Client with API key from environment variable
19
+ client = Together(api_key=os.getenv("TOGETHER_API_KEY", ""))
20
+
21
+ # Set device
22
+ 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)