NavyaNayer commited on
Commit
565359b
Β·
verified Β·
1 Parent(s): 131b751

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +484 -198
src/streamlit_app.py CHANGED
@@ -247,7 +247,7 @@ def get_llama_suggestion(emotion, tasks, selected_datetime):
247
  return f"Error generating AI plan: {e}"
248
 
249
 
250
- # Page Configuration
251
  st.set_page_config(
252
  page_title="πŸš€ AI Productivity Assistant",
253
  layout="wide",
@@ -257,219 +257,505 @@ st.set_page_config(
257
  # Custom CSS for enhanced styling
258
  st.markdown(get_custom_css(), unsafe_allow_html=True)
259
 
260
- # Title with custom styling
261
- st.markdown('<div class="main-header">🎯 MoodifyTask: AI Task Prioritization & Wellness Assistant</div>', unsafe_allow_html=True)
262
-
263
- # Initialize Session State
264
- if "tasks" not in st.session_state:
265
- st.session_state.tasks = []
266
- if "task_counter" not in st.session_state: # Add counter for unique IDs
267
- st.session_state.task_counter = 0
268
- if "overall_emotion" not in st.session_state:
269
- st.session_state.overall_emotion = None
270
- if "overall_emotion_label" not in st.session_state:
271
- st.session_state.overall_emotion_label = "Neutral"
272
-
273
- # Layout with improved spacing
274
- col1, col2 = st.columns([1, 1], gap="medium")
275
-
276
- with col1:
277
- # st.markdown('<div class="emotion-analysis">', unsafe_allow_html=True)
278
- st.markdown('<h3>🌟 Mood Analysis</h3>', unsafe_allow_html=True)
279
- emotion_sentence = st.text_area(
280
- "Describe how you're feeling today:",
281
- value="",
282
- height=150,
283
- help="Your emotional state helps us prioritize tasks more effectively"
284
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
285
 
286
- if emotion_sentence:
287
- emotion_score, emotion_label = predict_emotion(emotion_sentence)
288
- st.session_state.overall_emotion = emotion_score
289
- st.session_state.overall_emotion_label = emotion_label
290
-
291
- st.markdown(f'<div class="emotion-badge">Detected Emotion: {emotion_label}</div>', unsafe_allow_html=True)
292
-
293
- # Emotion-based task reprioritization
294
- for task in st.session_state.tasks:
295
- task["priority_score"] = calculate_priority_score(
296
- task["predicted_intent_score"],
297
- emotion_score,
298
- emotion_label,
299
- task["time_remaining"],
300
- task["complexity"],
301
- get_emotion_category(emotion_label)
302
- )
303
- st.markdown('</div>', unsafe_allow_html=True)
304
 
305
- with col2:
306
- # st.markdown('<div class="task-input">', unsafe_allow_html=True)
307
- st.markdown('<h3>πŸ“… Add New Task</h3>', unsafe_allow_html=True)
308
- with st.form("task_form", clear_on_submit=True):
309
- task_description = st.text_input("Task Description", help="Be specific about what needs to be done")
310
- col_date, col_time = st.columns(2)
311
 
312
- with col_date:
313
- due_date = st.date_input("Due Date")
314
-
315
- with col_time:
316
- due_time = st.time_input("Due Time")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
317
 
318
- complexity = st.slider(
319
- "Task Complexity (1-10)",
320
- 1, 10, 5,
321
- help="Higher complexity may affect task priority"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
322
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
323
 
324
- submitted = st.form_submit_button("βž• Add Task")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
325
 
326
- if submitted and task_description and due_date and due_time:
327
- due_date_time = datetime.combine(due_date, due_time)
328
- time_remaining = due_date_time - datetime.now()
329
- predicted_intent_score = predict_intent(task_description)
 
330
 
331
- task = {
332
- "id": st.session_state.task_counter, # Add unique ID
333
- "description": task_description,
334
- "due_date_time": due_date_time,
335
- "time_remaining": time_remaining,
336
- "complexity": complexity,
337
- "predicted_intent_score": predicted_intent_score,
338
- "predicted_emotion": st.session_state.overall_emotion,
339
- "predicted_label_name": st.session_state.overall_emotion_label,
340
- "priority_score": calculate_priority_score(
341
- predicted_intent_score,
342
- st.session_state.overall_emotion,
343
- st.session_state.overall_emotion_label,
344
- time_remaining,
345
- complexity,
346
- get_emotion_category(st.session_state.overall_emotion_label)
347
- ),
348
- "completed": False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
349
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
350
 
351
- st.session_state.tasks.append(task)
352
- st.session_state.task_counter += 1 # Increment counter
353
- st.success("βœ… Task Added Successfully!")
354
- st.markdown('</div>', unsafe_allow_html=True)
355
 
356
- # Task List with Improved Visualization
357
- if st.session_state.tasks:
358
- st.markdown('<h3>πŸ“Œ Task Priority List</h3>', unsafe_allow_html=True)
359
-
360
- # Sort tasks by priority
361
- sorted_tasks = sorted(st.session_state.tasks, key=lambda x: x["priority_score"], reverse=True)
362
-
363
- # Create task overview cards
364
- st.markdown('<div class="task-overview">', unsafe_allow_html=True)
365
- col1, col2 = st.columns(2)
366
  with col1:
367
- 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)
368
- # with col2:
369
- # high_priority = len([t for t in sorted_tasks if t["priority_score"] > 0.7])
370
- # 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)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
371
  with col2:
372
- today = datetime.now()
373
- due_today = len([t for t in sorted_tasks if t["due_date_time"].date() == today.date()])
374
- 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)
375
- st.markdown('</div>', unsafe_allow_html=True)
376
-
377
- # Display tasks with priority-based styling
378
- for idx, task in enumerate(sorted_tasks):
379
- priority_class = "high-priority" if task["priority_score"] > 0.7 else "medium-priority"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
380
 
381
- # Create a single row for task and buttons
382
- task_container = st.container()
383
- with task_container:
384
- cols = st.columns([0.8, 0.1, 0.1])
 
 
 
 
 
 
 
 
 
 
 
 
 
385
 
386
- # Task content in first column
387
- with cols[0]:
388
- st.markdown(f"""
389
- <div class="priority-task {priority_class}">
390
- <div class="task-content">
391
- <div class="task-header">
392
- <span class="task-title">{task["description"]}</span>
393
- <span class="priority-score">Priority: {task["priority_score"]:.2f}</span>
394
- </div>
395
- <div class="task-details">
396
- <span class="task-stat">Due: {task["due_date_time"].strftime("%d %b, %I:%M %p")}</span>
397
- <span class="task-stat">Complexity: {task["complexity"]}</span>
 
 
 
 
 
 
398
  </div>
399
  </div>
400
- </div>
401
- """, unsafe_allow_html=True)
402
- st.session_state.editing_task_id = None
403
- # Edit button
404
- with cols[1]:
405
- if st.button("✏️", key=f"edit_{idx}", help="Edit task"):
406
- st.session_state.editing_task_id = idx
407
-
408
- # Delete button
409
- with cols[2]:
410
- if st.button("πŸ—‘οΈ", key=f"delete_{idx}", help="Delete task"):
411
- st.session_state.tasks.pop(idx)
412
- st.success("Task deleted!")
413
- st.rerun()
414
-
415
- # Show edit form below the task if being edited
416
- if st.session_state.editing_task_id == idx:
417
- with st.form(key=f"edit_form_{idx}"):
418
- col1, col2 = st.columns(2)
419
- with col1:
420
- new_description = st.text_input("Description", value=task["description"])
421
- new_complexity = st.slider("Complexity", 1, 10, value=task["complexity"])
422
- with col2:
423
- new_due_date = st.date_input("Due Date", value=task["due_date_time"].date())
424
- new_due_time = st.time_input("Due Time", value=task["due_date_time"].time())
425
-
426
- col1, col2 = st.columns(2)
427
- with col1:
428
- if st.form_submit_button("πŸ’Ύ Save"):
429
- # Update task
430
- task["description"] = new_description
431
- task["due_date_time"] = datetime.combine(new_due_date, new_due_time)
432
- task["time_remaining"] = task["due_date_time"] - datetime.now()
433
- task["complexity"] = new_complexity
434
-
435
- # Recalculate priority
436
- task["priority_score"] = calculate_priority_score(
437
- task["predicted_intent_score"],
438
- task["predicted_emotion"],
439
- task["predicted_label_name"],
440
- task["time_remaining"],
441
- task["complexity"],
442
- get_emotion_category(task["predicted_label_name"])
443
- )
444
- st.session_state.editing_task_id = None
445
- st.success("Task updated!")
446
- st.rerun()
447
-
448
- with col2:
449
- if st.form_submit_button("❌ Cancel"):
450
- st.session_state.editing_task_id = None
451
- st.rerun()
452
-
453
- # AI Plan Section
454
- if st.session_state.tasks:
455
- st.markdown('<div class="custom-card">', unsafe_allow_html=True)
456
- st.markdown('<h3>⏰ AI Task Planning</h3>', unsafe_allow_html=True)
457
-
458
- col_date, col_time = st.columns(2)
459
-
460
- with col_date:
461
- plan_date = st.date_input("Select Plan Date", datetime.now().date())
462
-
463
- with col_time:
464
- plan_time = st.time_input("Select Plan Start Time", datetime.now().time())
465
-
466
- selected_datetime = datetime.combine(plan_date, plan_time)
467
 
468
- if st.button("πŸ“… Generate AI Plan"):
469
- suggestion = get_llama_suggestion(
470
- st.session_state.overall_emotion_label,
471
- st.session_state.tasks,
472
- selected_datetime # Pass full datetime object
473
- )
474
- st.markdown(f'<div class="info-box">{suggestion}</div>', unsafe_allow_html=True)
475
- st.markdown('</div>', unsafe_allow_html=True)
 
247
  return f"Error generating AI plan: {e}"
248
 
249
 
250
+ # Page Configuration first
251
  st.set_page_config(
252
  page_title="πŸš€ AI Productivity Assistant",
253
  layout="wide",
 
257
  # Custom CSS for enhanced styling
258
  st.markdown(get_custom_css(), unsafe_allow_html=True)
259
 
260
+ # Show loading screen if models aren't ready
261
+ if not st.session_state.is_ready:
262
+ st.markdown(
263
+ """
264
+ <div class="loading-container" style="text-align: center; padding: 50px;">
265
+ <div class="loading-spinner"></div>
266
+ <h2>Setting up your AI assistant...</h2>
267
+ <p>This may take a minute. We're downloading the required models.</p>
268
+ </div>
269
+ """,
270
+ unsafe_allow_html=True
 
 
 
 
 
 
 
 
 
 
 
 
 
271
  )
272
+
273
+ # Load models here
274
+ try:
275
+ # First download pretrained models
276
+ if not os.path.exists("pretrained_models"):
277
+ with st.status("Downloading base models...", expanded=True) as status:
278
+ os.makedirs("pretrained_models", exist_ok=True)
279
+ gdown.download_folder(
280
+ f"https://drive.google.com/drive/folders/{pretrained_folder_id}",
281
+ output="pretrained_models",
282
+ quiet=False
283
+ )
284
+ status.update(label="Base models downloaded!", state="complete")
285
+
286
+ # Intent Model Loading
287
+ if not os.path.exists(intent_model_path):
288
+ with st.status("Downloading intent model...", expanded=True) as status:
289
+ output = gdown.download(
290
+ f"https://drive.google.com/uc?id={file_id}",
291
+ intent_model_path,
292
+ quiet=False
293
+ )
294
+ status.update(label="Intent model downloaded!", state="complete")
295
+
296
+ # Emotion Model Loading
297
+ if not os.path.exists(emotions_model_path):
298
+ with st.status("Downloading emotion model...", expanded=True) as status:
299
+ os.makedirs(emotions_model_path, exist_ok=True)
300
+ gdown.download_folder(
301
+ f"https://drive.google.com/drive/folders/{emotions_folder_id}",
302
+ output=emotions_model_path,
303
+ quiet=False
304
+ )
305
+ status.update(label="Emotion model downloaded!", state="complete")
306
+
307
+ # Load and store intent model
308
+ intent_model = AutoModelForSequenceClassification.from_pretrained(
309
+ "pretrained_models/bert-base-uncased",
310
+ num_labels=num_intent_labels,
311
+ ignore_mismatched_sizes=True, # Add this parameter
312
+ local_files_only=True
313
+ )
314
+ intent_model.load_state_dict(
315
+ torch.load(intent_model_path, map_location=device, weights_only=True)
316
+ )
317
+ st.session_state.models["intent_model"] = intent_model.to(device).eval()
318
+ st.session_state.models["intent_tokenizer"] = AutoTokenizer.from_pretrained(
319
+ "pretrained_models/bert-base-uncased",
320
+ local_files_only=True
321
+ )
322
 
323
+ # Load and store emotion model
324
+ emotions_model = AutoModelForSequenceClassification.from_pretrained(
325
+ emotions_model_path,
326
+ ignore_mismatched_sizes=True, # Add this parameter
327
+ local_files_only=True
328
+ )
329
+ st.session_state.models["emotions_model"] = emotions_model.to(device).eval()
330
+ st.session_state.models["emotions_tokenizer"] = AutoTokenizer.from_pretrained(
331
+ emotions_model_path,
332
+ local_files_only=True
333
+ )
 
 
 
 
 
 
 
334
 
335
+ # Set ready state
336
+ st.session_state.is_ready = True
337
+ st.rerun()
 
 
 
338
 
339
+ except Exception as e:
340
+ st.error(f"Error loading models: {str(e)}")
341
+ st.stop()
342
+
343
+ # Only show main app if models are ready
344
+ if st.session_state.is_ready:
345
+ # Title with custom styling
346
+ st.markdown('<div class="main-header">🎯 MoodifyTask: AI Task Prioritization & Wellness Assistant</div>', unsafe_allow_html=True)
347
+
348
+ # Emotion Labels
349
+ emotion_label_names = [
350
+ "admiration", "amusement", "anger", "annoyance", "approval",
351
+ "caring", "confusion", "curiosity", "desire", "disappointment",
352
+ "disapproval", "disgust", "embarrassment", "excitement", "fear",
353
+ "gratitude", "grief", "joy", "love", "nervousness",
354
+ "optimism", "pride", "realization", "relief", "remorse",
355
+ "sadness", "surprise", "neutral"
356
+ ]
357
+
358
+ # Emotion Categories
359
+ positive_emotions = ["admiration", "amusement", "approval", "caring", "curiosity", "excitement", "gratitude", "joy", "love", "optimism", "pride", "relief", "surprise"]
360
+ negative_emotions = ["anger", "annoyance", "disappointment", "disapproval", "disgust", "embarrassment", "fear", "grief", "nervousness", "remorse", "sadness"]
361
+ neutral_emotions = ["realization", "neutral"]
362
+
363
+ # Predict Intent
364
+ def predict_intent(sentence):
365
+ inputs = st.session_state.models["intent_tokenizer"](
366
+ sentence, return_tensors="pt", padding="max_length", truncation=True, max_length=128
367
+ )
368
+ inputs = {key: val.to(device) for key, val in inputs.items()}
369
+ with torch.no_grad():
370
+ outputs = st.session_state.models["intent_model"](**inputs)
371
+ predicted_class = torch.argmax(outputs.logits, dim=1).cpu().numpy()[0]
372
 
373
+ # Mapping Intent IDs to Priorities (0-150)
374
+ PRIORITY_MAPPING = {
375
+ 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
376
+ 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
377
+ 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
378
+ 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
379
+ 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]
380
+ # 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
381
+ }
382
+
383
+ # Find the priority based on predicted_class
384
+ predicted_intent_score = next((priority for priority, ids in PRIORITY_MAPPING.items() if predicted_class in ids), 1) # Default to 1 if not found
385
+
386
+ return predicted_intent_score
387
+
388
+ # Emotion to Numeric Score Mapping
389
+ EMOTION_MAPPING = {
390
+ "admiration": 4, "amusement": 3, "anger": 5, "annoyance": 4, "approval": 3,
391
+ "caring": 4, "confusion": 3, "curiosity": 3, "desire": 4, "disappointment": 4,
392
+ "disapproval": 4, "disgust": 5, "embarrassment": 4, "excitement": 5, "fear": 5,
393
+ "gratitude": 3, "grief": 5, "joy": 5, "love": 5, "nervousness": 4,
394
+ "optimism": 4, "pride": 4, "realization": 3, "relief": 3, "remorse": 4,
395
+ "sadness": 5, "surprise": 3, "neutral": 3
396
+ }
397
+
398
+ # Function to get numeric emotion score
399
+ def get_emotion_score(emotion):
400
+ return EMOTION_MAPPING.get(emotion.lower(), 3) # Default to 3 if not found
401
+ # Predict Emotion
402
+ def predict_emotion(sentence):
403
+ if not sentence.strip():
404
+ return 3, "neutral"
405
+ # Ensure the input is a full sentence
406
+ if len(sentence.split()) == 1:
407
+ sentence = f"I feel {sentence}"
408
+ inputs = st.session_state.models["emotions_tokenizer"](
409
+ sentence, return_tensors="pt", padding="max_length", truncation=True, max_length=128
410
  )
411
+ inputs = {key: val.to(device) for key, val in inputs.items() if key != "token_type_ids"}
412
+
413
+ with torch.no_grad():
414
+ outputs = st.session_state.models["emotions_model"](**inputs)
415
+ predicted_class = torch.argmax(outputs.logits, dim=1).cpu().numpy()[0]
416
+
417
+ detected_emotion = emotion_label_names[predicted_class]
418
+
419
+ # Manually adjust for stress/pressure-related words
420
+ stress_keywords = ["stress", "stressed", "overwhelmed", "pressure", "tense", "burnout"]
421
+ if any(word in sentence.lower() for word in stress_keywords):
422
+ if detected_emotion not in ["sadness", "nervousness"]:
423
+ detected_emotion = "nervousness" # Change to "sadness" if you prefer
424
+
425
+ emotion_score = get_emotion_score(detected_emotion)
426
+ if emotion_score is None:
427
+ emotion_score = 3 # Default neutral score
428
+
429
+ return emotion_score, detected_emotion
430
+
431
+
432
+ # Get Emotion Category
433
+ def get_emotion_category(emotion):
434
+ if emotion in positive_emotions:
435
+ return "positive"
436
+ elif emotion in negative_emotions:
437
+ return "negative"
438
+ else:
439
+ return "neutral"
440
 
441
+
442
+ def normalize_priority(priority, min_value=0, max_value=10):
443
+ return (priority - min_value) / (max_value - min_value) # Normalize between 0-1
444
+
445
+ # Calculate Task Priority
446
+ def calculate_priority_score(predicted_intent_score,emotion_score, emotion, time_remaining, complexity, emotion_category):
447
+ """
448
+ Calculate an adaptive priority score for tasks based on intent, emotion, time urgency, and complexity.
449
+ """
450
+ emotion_score = emotion_score if emotion_score is not None else 3
451
+ # Normalize time urgency (scale 0 to 1 based on 7 days)
452
+ time_score = max(0, min(1, 1 - (time_remaining.total_seconds() / (7 * 24 * 3600))))
453
+
454
+ # Set emotion-based adjustments
455
+ stress_emotions = ["nervousness", "sadness", "fear"]
456
+ frustration_emotions = ["anger", "frustration","disappointment","annoyance"]
457
+ anxiety_emotions = ["anxiety", "uncertainty"]
458
 
459
+
460
+ if emotion_category == "negative":
461
+ if emotion in stress_emotions:
462
+ # Prioritize **easy, quick** tasks to reduce cognitive load
463
+ priority = (predicted_intent_score * 0.15) + (emotion_score * 0.1) + (time_score * 0.3) + ((10 - complexity) * 0.45)
464
 
465
+ elif emotion in frustration_emotions:
466
+ # Prioritize **engaging** tasks (not too easy) but keep urgency in mind
467
+ priority = (predicted_intent_score * 0.2) + (emotion_score * 0.15) + (time_score * 0.25) + (complexity * 0.4)
468
+
469
+ elif emotion in anxiety_emotions:
470
+ # Prioritize **urgent, low-complexity** tasks
471
+ priority = (predicted_intent_score * 0.2) + (emotion_score * 0.1) + (time_score * 0.4) + ((10 - complexity) * 0.3)
472
+
473
+ else:
474
+ # Default for negative emotions: balance urgency and ease
475
+ priority = (predicted_intent_score * 0.2) + (emotion_score * 0.1) + (time_score * 0.3) + ((10 - complexity) * 0.4)
476
+
477
+ elif emotion_category == "positive":
478
+ # If the user is in a **good mood**, favor challenging, high-impact tasks
479
+ priority = (predicted_intent_score * 0.35) + (emotion_score * 0.2) + (time_score * 0.25) + (complexity * 0.2)
480
+
481
+ else: # Neutral emotion
482
+ # Keep a balance between difficulty and urgency
483
+ priority = (predicted_intent_score * 0.3) + (emotion_score * 0.2) + (time_score * 0.2) + (complexity * 0.3)
484
+
485
+ return normalize_priority(priority) # Ensure no negative priority values
486
+
487
+
488
+
489
+
490
+ # AI-Generated Plan Based on Start Time
491
+ from datetime import datetime
492
+
493
+ def get_llama_suggestion(emotion, tasks, selected_datetime):
494
+ """Generate AI plan based on full datetime instead of just time"""
495
+ # Sort tasks by priority (higher priority first)
496
+ sorted_tasks = sorted(tasks, key=lambda x: x["priority_score"], reverse=True)
497
+
498
+ # Filter tasks based on selected datetime
499
+ filtered_tasks = [
500
+ task for task in sorted_tasks
501
+ if task["due_date_time"] >= selected_datetime
502
+ ]
503
+
504
+ if not filtered_tasks:
505
+ well_being_prompts = {
506
+ "nervousness": "Suggest mindfulness exercises and short relaxation techniques.",
507
+ "sadness": "Suggest comforting activities like journaling or light exercise.",
508
+ "anger": "Suggest ways to channel frustration productively.",
509
+ "joy": "Suggest ways to maintain productivity while feeling good.",
510
+ "neutral": "Suggest general relaxation activities like listening to music."
511
  }
512
+ well_being_prompt = f"""
513
+ The user is feeling {emotion}.
514
+ They have no tasks scheduled after {selected_datetime.strftime('%B %d, %I:%M %p')}.
515
+ {well_being_prompts.get(emotion, 'Provide general well-being tips.')}
516
+ """
517
+ try:
518
+ response = client.chat.completions.create(
519
+ messages=[{"role": "user", "content": well_being_prompt}],
520
+ model="meta-llama/Llama-3.3-70B-Instruct-Turbo",
521
+ temperature=0.7,
522
+ )
523
+ return response.choices[0].message.content
524
+ except Exception as e:
525
+ return f"Error generating well-being tips: {e}"
526
+
527
+ # Prepare the prompt with more detailed datetime information
528
+ task_details = "\n".join([
529
+ f"- {task['description']} (Priority: {task['priority_score']:.2f}, Complexity: {task['complexity']}, Due: {task['due_date_time'].strftime('%B %d, %I:%M %p')})"
530
+ for task in filtered_tasks
531
+ ])
532
+
533
+ prompt = f"""
534
+ The user is feeling {emotion}.
535
+ They need a structured productivity plan starting from {selected_datetime.strftime('%B %d, %I:%M %p')}, not the current time.
536
+
537
+ Their prioritized tasks (due on or after the selected time), sorted by priority score:
538
+ {task_details}
539
+
540
+ Please provide:
541
+ 1. A detailed schedule with specific times for each task
542
+ 2. Strategic breaks based on task complexity and emotional state
543
+ 3. Wellness activities that complement their current emotion
544
+ 4. Tips for managing tasks effectively given their emotional state
545
+ 5. Suggestions for handling high-priority tasks first while maintaining well-being
546
+ """
547
+
548
+ try:
549
+ response = client.chat.completions.create(
550
+ messages=[{"role": "user", "content": prompt}],
551
+ model="meta-llama/Llama-3.3-70B-Instruct-Turbo",
552
+ temperature=0.7,
553
+ )
554
+ return response.choices[0].message.content
555
+ except Exception as e:
556
+ return f"Error generating AI plan: {e}"
557
 
 
 
 
 
558
 
559
+ # Layout with improved spacing
560
+ col1, col2 = st.columns([1, 1], gap="medium")
561
+
 
 
 
 
 
 
 
562
  with col1:
563
+ # st.markdown('<div class="emotion-analysis">', unsafe_allow_html=True)
564
+ st.markdown('<h3>🌟 Mood Analysis</h3>', unsafe_allow_html=True)
565
+ emotion_sentence = st.text_area(
566
+ "Describe how you're feeling today:",
567
+ value="",
568
+ height=150,
569
+ help="Your emotional state helps us prioritize tasks more effectively"
570
+ )
571
+
572
+ if emotion_sentence:
573
+ emotion_score, emotion_label = predict_emotion(emotion_sentence)
574
+ st.session_state.overall_emotion = emotion_score
575
+ st.session_state.overall_emotion_label = emotion_label
576
+
577
+ st.markdown(f'<div class="emotion-badge">Detected Emotion: {emotion_label}</div>', unsafe_allow_html=True)
578
+
579
+ # Emotion-based task reprioritization
580
+ for task in st.session_state.tasks:
581
+ task["priority_score"] = calculate_priority_score(
582
+ task["predicted_intent_score"],
583
+ emotion_score,
584
+ emotion_label,
585
+ task["time_remaining"],
586
+ task["complexity"],
587
+ get_emotion_category(emotion_label)
588
+ )
589
+ st.markdown('</div>', unsafe_allow_html=True)
590
+
591
  with col2:
592
+ # st.markdown('<div class="task-input">', unsafe_allow_html=True)
593
+ st.markdown('<h3>πŸ“… Add New Task</h3>', unsafe_allow_html=True)
594
+ with st.form("task_form", clear_on_submit=True):
595
+ task_description = st.text_input("Task Description", help="Be specific about what needs to be done")
596
+ col_date, col_time = st.columns(2)
597
+
598
+ with col_date:
599
+ due_date = st.date_input("Due Date")
600
+
601
+ with col_time:
602
+ due_time = st.time_input("Due Time")
603
+
604
+ complexity = st.slider(
605
+ "Task Complexity (1-10)",
606
+ 1, 10, 5,
607
+ help="Higher complexity may affect task priority"
608
+ )
609
+
610
+ submitted = st.form_submit_button("βž• Add Task")
611
+
612
+ if submitted and task_description and due_date and due_time:
613
+ due_date_time = datetime.combine(due_date, due_time)
614
+ time_remaining = due_date_time - datetime.now()
615
+ predicted_intent_score = predict_intent(task_description)
616
+
617
+ task = {
618
+ "id": st.session_state.task_counter, # Add unique ID
619
+ "description": task_description,
620
+ "due_date_time": due_date_time,
621
+ "time_remaining": time_remaining,
622
+ "complexity": complexity,
623
+ "predicted_intent_score": predicted_intent_score,
624
+ "predicted_emotion": st.session_state.overall_emotion,
625
+ "predicted_label_name": st.session_state.overall_emotion_label,
626
+ "priority_score": calculate_priority_score(
627
+ predicted_intent_score,
628
+ st.session_state.overall_emotion,
629
+ st.session_state.overall_emotion_label,
630
+ time_remaining,
631
+ complexity,
632
+ get_emotion_category(st.session_state.overall_emotion_label)
633
+ ),
634
+ "completed": False
635
+ }
636
+
637
+ st.session_state.tasks.append(task)
638
+ st.session_state.task_counter += 1 # Increment counter
639
+ st.success("βœ… Task Added Successfully!")
640
+ st.markdown('</div>', unsafe_allow_html=True)
641
+
642
+ # Task List with Improved Visualization
643
+ if st.session_state.tasks:
644
+ st.markdown('<h3>πŸ“Œ Task Priority List</h3>', unsafe_allow_html=True)
645
+
646
+ # Sort tasks by priority
647
+ sorted_tasks = sorted(st.session_state.tasks, key=lambda x: x["priority_score"], reverse=True)
648
 
649
+ # Create task overview cards
650
+ st.markdown('<div class="task-overview">', unsafe_allow_html=True)
651
+ col1, col2 = st.columns(2)
652
+ with col1:
653
+ 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)
654
+ # with col2:
655
+ # high_priority = len([t for t in sorted_tasks if t["priority_score"] > 0.7])
656
+ # 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)
657
+ with col2:
658
+ today = datetime.now()
659
+ due_today = len([t for t in sorted_tasks if t["due_date_time"].date() == today.date()])
660
+ 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)
661
+ st.markdown('</div>', unsafe_allow_html=True)
662
+
663
+ # Display tasks with priority-based styling
664
+ for idx, task in enumerate(sorted_tasks):
665
+ priority_class = "high-priority" if task["priority_score"] > 0.7 else "medium-priority"
666
 
667
+ # Create a single row for task and buttons
668
+ task_container = st.container()
669
+ with task_container:
670
+ cols = st.columns([0.8, 0.1, 0.1])
671
+
672
+ # Task content in first column
673
+ with cols[0]:
674
+ st.markdown(f"""
675
+ <div class="priority-task {priority_class}">
676
+ <div class="task-content">
677
+ <div class="task-header">
678
+ <span class="task-title">{task["description"]}</span>
679
+ <span class="priority-score">Priority: {task["priority_score"]:.2f}</span>
680
+ </div>
681
+ <div class="task-details">
682
+ <span class="task-stat">Due: {task["due_date_time"].strftime("%d %b, %I:%M %p")}</span>
683
+ <span class="task-stat">Complexity: {task["complexity"]}</span>
684
+ </div>
685
  </div>
686
  </div>
687
+ """, unsafe_allow_html=True)
688
+ st.session_state.editing_task_id = None
689
+ # Edit button
690
+ with cols[1]:
691
+ if st.button("✏️", key=f"edit_{idx}", help="Edit task"):
692
+ st.session_state.editing_task_id = idx
693
+
694
+ # Delete button
695
+ with cols[2]:
696
+ if st.button("πŸ—‘οΈ", key=f"delete_{idx}", help="Delete task"):
697
+ st.session_state.tasks.pop(idx)
698
+ st.success("Task deleted!")
699
+ st.rerun()
700
+
701
+ # Show edit form below the task if being edited
702
+ if st.session_state.editing_task_id == idx:
703
+ with st.form(key=f"edit_form_{idx}"):
704
+ col1, col2 = st.columns(2)
705
+ with col1:
706
+ new_description = st.text_input("Description", value=task["description"])
707
+ new_complexity = st.slider("Complexity", 1, 10, value=task["complexity"])
708
+ with col2:
709
+ new_due_date = st.date_input("Due Date", value=task["due_date_time"].date())
710
+ new_due_time = st.time_input("Due Time", value=task["due_date_time"].time())
711
+
712
+ col1, col2 = st.columns(2)
713
+ with col1:
714
+ if st.form_submit_button("πŸ’Ύ Save"):
715
+ # Update task
716
+ task["description"] = new_description
717
+ task["due_date_time"] = datetime.combine(new_due_date, new_due_time)
718
+ task["time_remaining"] = task["due_date_time"] - datetime.now()
719
+ task["complexity"] = new_complexity
720
+
721
+ # Recalculate priority
722
+ task["priority_score"] = calculate_priority_score(
723
+ task["predicted_intent_score"],
724
+ task["predicted_emotion"],
725
+ task["predicted_label_name"],
726
+ task["time_remaining"],
727
+ task["complexity"],
728
+ get_emotion_category(task["predicted_label_name"])
729
+ )
730
+ st.session_state.editing_task_id = None
731
+ st.success("Task updated!")
732
+ st.rerun()
733
+
734
+ with col2:
735
+ if st.form_submit_button("❌ Cancel"):
736
+ st.session_state.editing_task_id = None
737
+ st.rerun()
738
+
739
+ # AI Plan Section
740
+ if st.session_state.tasks:
741
+ st.markdown('<div class="custom-card">', unsafe_allow_html=True)
742
+ st.markdown('<h3>⏰ AI Task Planning</h3>', unsafe_allow_html=True)
743
+
744
+ col_date, col_time = st.columns(2)
745
+
746
+ with col_date:
747
+ plan_date = st.date_input("Select Plan Date", datetime.now().date())
748
+
749
+ with col_time:
750
+ plan_time = st.time_input("Select Plan Start Time", datetime.now().time())
751
+
752
+ selected_datetime = datetime.combine(plan_date, plan_time)
 
753
 
754
+ if st.button("πŸ“… Generate AI Plan"):
755
+ suggestion = get_llama_suggestion(
756
+ st.session_state.overall_emotion_label,
757
+ st.session_state.tasks,
758
+ selected_datetime # Pass full datetime object
759
+ )
760
+ st.markdown(f'<div class="info-box">{suggestion}</div>', unsafe_allow_html=True)
761
+ st.markdown('</div>', unsafe_allow_html=True)