Updated Chatbot and Report Generator

#2
Files changed (1) hide show
  1. app.py +453 -98
app.py CHANGED
@@ -1,14 +1,17 @@
1
  import json
2
  import os
3
  import copy
 
 
4
  import streamlit as st
5
  from openai import OpenAI
6
- from datetime import datetime
7
  from langchain_openai import ChatOpenAI
 
8
  from typing import Annotated, List
9
  from pydantic import BaseModel, Field
10
  from typing_extensions import TypedDict, Literal
11
  from langgraph.graph import StateGraph, START, END
 
12
 
13
  # Page configuration
14
  st.set_page_config(layout="wide", page_title="JEE Roadmap Planner")
@@ -18,6 +21,8 @@ if "data" not in st.session_state:
18
  st.session_state.data = None
19
  if "data_old" not in st.session_state:
20
  st.session_state.data_old = None
 
 
21
  if "incomplete_tasks" not in st.session_state:
22
  st.session_state.incomplete_tasks = None
23
  if "incomplete_task_list" not in st.session_state:
@@ -39,24 +44,46 @@ page = st.sidebar.radio("Navigation", ["Home", "Roadmap Manager", "Task Analysis
39
 
40
 
41
  # For roadmap chatbot
42
- import sqlite3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
  # Function to convert NL query to SQL
45
  def generate_sql_from_nl(prompt):
46
  client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
47
 
48
- table_struct = """
49
- CREATE TABLE IF NOT EXISTS roadmap (
50
- id INTEGER PRIMARY KEY AUTOINCREMENT,
51
- day_num INTEGER,
52
- date TEXT,
53
- subject TEXT,
54
- chapter_name TEXT,
55
- task_type TEXT,
56
- time TEXT,
57
- subtopic TEXT
58
- )
59
- """
60
 
61
  response = client.chat.completions.create(
62
  model="gpt-4o-mini",
@@ -66,14 +93,19 @@ def generate_sql_from_nl(prompt):
66
  create an SQL query to extract the related Information from an sqlite3 database with the table
67
  structure: {table_struct}.
68
 
69
- Note: For the time column, the data is formatted like '0.5 hour', '1 hour', '2 hours' and
70
- so on. So make sure create queries that compare just the numbers within the text.
71
-
 
 
 
 
72
  You will also make sure multiple times that you give an SQL
73
  Query that adheres to the given table structure, and you Output just the SQL query.
74
  Do not include anyting else like new line statements, ```sql or any other text. Your output
75
  is going to be directly fed into a Python script to extract the required information. So,
76
- please follow all the given Instructions."""},
 
77
  {"role": "user", "content": f"""Keeping the table structure in mind: {table_struct},
78
  Convert this prompt to an SQL query for the given table: {prompt}. Make sure your
79
  output is just the SQL query, which can directly be used to extract required content"""}
@@ -82,7 +114,7 @@ def generate_sql_from_nl(prompt):
82
  return response.choices[0].message.content.strip()
83
 
84
  # Function to convert SQL output to natural language
85
- def generate_nl_from_sql_output(prompt, data):
86
  client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
87
 
88
  response = client.chat.completions.create(
@@ -93,7 +125,8 @@ def generate_nl_from_sql_output(prompt, data):
93
  You are going to play a very crucial role of a Roadmap Assistant, who helps the student out with whatever query
94
  they have related to their roadmap, the data required to answer the users query is already extracted
95
  from the Roadmap table of a SQLite3 database and given to you here {data}. Analyse the users query deeply and
96
- reply to it with the relevant information from the given data in a supportive manner."""},
 
97
  {"role": "user", "content": f"""Answer to this users query using the data given to you, while keeping
98
  your role in mind: {prompt}"""}
99
  ]
@@ -112,11 +145,11 @@ def fetch_data_from_sql(sql_query):
112
  # Main function for chatbot
113
  def answer_user_query(prompt):
114
  initialize_roadmap_db()
115
- sql = generate_sql_from_nl(prompt)
116
- st.write(sql)
117
- rows = fetch_data_from_sql(sql)
118
  st.write(rows)
119
- return generate_nl_from_sql_output(prompt, rows)
120
 
121
  def initialize_roadmap_db():
122
  if not os.path.exists("jee_roadmap.db"):
@@ -164,6 +197,7 @@ def initialize_roadmap_db():
164
  print("✅ Database created and data inserted successfully.")
165
  except Exception as e:
166
  print(f"⚠️ Error initializing database: {e}")
 
167
  # Function to load initial data
168
  def load_initial_data():
169
  with st.spinner("Loading roadmap data..."):
@@ -244,34 +278,349 @@ def extract_incomplete_tasks():
244
  st.session_state.incomplete_task_list = incomplete_task_list
245
  st.success("Incomplete tasks extracted!")
246
 
247
- # Function to generate report
248
- def generate_report():
249
- with st.spinner("Generating performance report using AI..."):
250
- previous_day = st.session_state.data["schedule"][0]
251
- previous_day_roadmap_str = str(previous_day)
252
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253
  try:
254
- client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
255
- response = client.chat.completions.create(
256
- model="gpt-4o-mini",
257
- messages=[
258
- {"role": "system", "content": """You will be given a JEE student's previous_day_roadmap and then you have to create
259
- a completely interactive and useful report for the user.
260
- The report should include a table for task completion rates and data
261
- The student's study pattern
262
- The student's weaknesses and tips to improve.
263
- Make sure that a task is completed only when the "task_completed" key is true and the "time" key tells about how much
264
- tentative that task can take time
265
- Use markdown formatting.
266
- """},
267
- {"role": "user", "content": f"""Here is the user's previous day roadmap in json : {previous_day_roadmap_str}"""}
268
- ]
269
- )
270
- output = response.choices[0].message.content
271
- st.session_state.final_report = output
272
- st.success("Report generated successfully!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
273
  except Exception as e:
274
- st.error(f"Error generating report: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
275
 
276
  # Function to extract available dates
277
  def extract_available_dates():
@@ -301,7 +650,7 @@ def shift_incomplete_tasks():
301
  with st.spinner("Optimizing task distribution using evaluator-optimizer approach..."):
302
  try:
303
  # Initialize needed components
304
- llm = ChatOpenAI(model="gpt-4o-mini")
305
 
306
  # Schema for structured output to use in evaluation
307
  class Feedback(BaseModel):
@@ -655,57 +1004,63 @@ elif page == "Roadmap Manager":
655
  elif page == "Task Analysis":
656
  st.title("📊 Task Analysis")
657
 
658
- if st.session_state.data is None:
659
- st.warning("Please load roadmap data first from the Home page.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
660
  else:
661
- st.markdown("### Performance Report")
662
-
663
- if st.button("🔍 Generate Performance Report"):
664
- generate_report()
665
-
666
- if st.session_state.final_report:
667
- st.markdown(st.session_state.final_report)
668
- else:
669
- st.info("Click the button above to generate your performance report.")
670
 
671
- # Add visualization options
672
- if st.session_state.data:
673
- st.subheader("Task Breakdown")
 
 
674
 
675
- # Simple task statistics
676
- if st.checkbox("Show Task Statistics"):
677
- task_count = 0
678
- subject_counts = {}
679
- type_counts = {}
680
-
681
- for day in st.session_state.data["schedule"]:
682
- for subject in day["subjects"]:
683
- subject_name = subject["name"]
684
- if subject_name not in subject_counts:
685
- subject_counts[subject_name] = 0
686
 
687
- for task in subject["tasks"]:
688
- subject_counts[subject_name] += 1
689
- task_count += 1
690
-
691
- # Count by task type
692
- task_type = task.get("type", "Unknown")
693
- if task_type not in type_counts:
694
- type_counts[task_type] = 0
695
- type_counts[task_type] += 1
696
-
697
- st.write(f"Total tasks: {task_count}")
698
-
699
- # Create charts for data visualization
700
- col1, col2 = st.columns(2)
701
-
702
- with col1:
703
- st.subheader("Subject Distribution")
704
- st.bar_chart(subject_counts)
705
-
706
- with col2:
707
- st.subheader("Task Type Distribution")
708
- st.bar_chart(type_counts)
709
  # ---- ROADMAP CHATBOT PAGE ----
710
  elif page == "Roadmap Chatbot":
711
  st.title("🤖 Roadmap Chatbot Assistant")
 
1
  import json
2
  import os
3
  import copy
4
+ import sqlite3
5
+ import operator
6
  import streamlit as st
7
  from openai import OpenAI
 
8
  from langchain_openai import ChatOpenAI
9
+ from langchain_core.messages import HumanMessage, SystemMessage
10
  from typing import Annotated, List
11
  from pydantic import BaseModel, Field
12
  from typing_extensions import TypedDict, Literal
13
  from langgraph.graph import StateGraph, START, END
14
+ from langgraph.constants import Send
15
 
16
  # Page configuration
17
  st.set_page_config(layout="wide", page_title="JEE Roadmap Planner")
 
21
  st.session_state.data = None
22
  if "data_old" not in st.session_state:
23
  st.session_state.data_old = None
24
+ if "report_data" not in st.session_state:
25
+ st.session_state.report_data = None
26
  if "incomplete_tasks" not in st.session_state:
27
  st.session_state.incomplete_tasks = None
28
  if "incomplete_task_list" not in st.session_state:
 
44
 
45
 
46
  # For roadmap chatbot
47
+ def get_chapters_and_subtopics():
48
+ with open("full_roadmap.json", "r") as f:
49
+ data = json.load(f)
50
+
51
+ ch_subt = {
52
+ "Physics": {},
53
+ "Chemistry": {},
54
+ "Maths": {}
55
+ }
56
+
57
+ for day in data["schedule"]:
58
+ for subject in day['subjects']:
59
+ sub = ch_subt[subject['name']]
60
+ for task in subject['tasks']:
61
+ sub[task['ChapterName']] = []
62
+
63
+ for day in data["schedule"]:
64
+ for subject in day['subjects']:
65
+ sub = ch_subt[subject['name']]
66
+ for task in subject['tasks']:
67
+ sub[task['ChapterName']].append(task['subtopic'])
68
+
69
+ return ch_subt
70
 
71
  # Function to convert NL query to SQL
72
  def generate_sql_from_nl(prompt):
73
  client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
74
 
75
+ table_struct = """CREATE TABLE IF NOT EXISTS roadmap (
76
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
77
+ day_num INTEGER,
78
+ date TEXT, -- [yyyy-mm-dd]
79
+ subject TEXT, -- [Physics, Chemistry or Maths]
80
+ chapter_name TEXT,
81
+ task_type TEXT, -- (Concept Understanding, Question Practice, Revision, Test)
82
+ time TEXT, -- formatted like '0.5 hour', '1 hour', '2 Hours', and so on
83
+ subtopic TEXT,
84
+ )"""
85
+
86
+ ch_subt = get_chapters_and_subtopics()
87
 
88
  response = client.chat.completions.create(
89
  model="gpt-4o-mini",
 
93
  create an SQL query to extract the related Information from an sqlite3 database with the table
94
  structure: {table_struct}.
95
 
96
+ Note:
97
+ - For the time column, the data is formatted like '0.5 hour', '1 hour', '2 hours' and
98
+ so on. So make sure to create queries that compare just the numbers within the text.
99
+ - If the student mention about any chapters or subtopics, browse through this json file {ch_subt},
100
+ find the one with the closest match to the users query and use only those exact names of Chapers
101
+ and Subtopics present in this file to create SQL the query.
102
+
103
  You will also make sure multiple times that you give an SQL
104
  Query that adheres to the given table structure, and you Output just the SQL query.
105
  Do not include anyting else like new line statements, ```sql or any other text. Your output
106
  is going to be directly fed into a Python script to extract the required information. So,
107
+ please follow all the given Instructions.
108
+ """},
109
  {"role": "user", "content": f"""Keeping the table structure in mind: {table_struct},
110
  Convert this prompt to an SQL query for the given table: {prompt}. Make sure your
111
  output is just the SQL query, which can directly be used to extract required content"""}
 
114
  return response.choices[0].message.content.strip()
115
 
116
  # Function to convert SQL output to natural language
117
+ def generate_nl_from_sql_output(prompt, query, data):
118
  client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
119
 
120
  response = client.chat.completions.create(
 
125
  You are going to play a very crucial role of a Roadmap Assistant, who helps the student out with whatever query
126
  they have related to their roadmap, the data required to answer the users query is already extracted
127
  from the Roadmap table of a SQLite3 database and given to you here {data}. Analyse the users query deeply and
128
+ reply to it with the relevant information from the given data in a supportive manner. If you get empty data
129
+ as an input, deeply analyze the user's prompt and the sql query and give a suitable reply."""},
130
  {"role": "user", "content": f"""Answer to this users query using the data given to you, while keeping
131
  your role in mind: {prompt}"""}
132
  ]
 
145
  # Main function for chatbot
146
  def answer_user_query(prompt):
147
  initialize_roadmap_db()
148
+ query = generate_sql_from_nl(prompt)
149
+ st.write(query)
150
+ rows = fetch_data_from_sql(query)
151
  st.write(rows)
152
+ return generate_nl_from_sql_output(prompt, query, rows)
153
 
154
  def initialize_roadmap_db():
155
  if not os.path.exists("jee_roadmap.db"):
 
197
  print("✅ Database created and data inserted successfully.")
198
  except Exception as e:
199
  print(f"⚠️ Error initializing database: {e}")
200
+
201
  # Function to load initial data
202
  def load_initial_data():
203
  with st.spinner("Loading roadmap data..."):
 
278
  st.session_state.incomplete_task_list = incomplete_task_list
279
  st.success("Incomplete tasks extracted!")
280
 
281
+ def generate_sql_for_report(llm, prompt):
282
+ table_struct = """
283
+ CREATE TABLE IF NOT EXISTS roadmap (
284
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
285
+ day_num INTEGER,
286
+ date TEXT,
287
+ subject TEXT,
288
+ chapter_name TEXT,
289
+ task_type TEXT,
290
+ time TEXT,
291
+ subtopic TEXT,
292
+ task_completed BOOLEAN,
293
+ completion_timestamp TEXT
294
+ )
295
+ """
296
+
297
+ response = llm.invoke(
298
+ [
299
+ SystemMessage(content=f"""You are a helper who runs in the background of an AI agent,
300
+ which helps students for their JEE Preparation. Now your job is to analyze the user's prompt and
301
+ create an SQL query to extract the related Information from an sqlite3 database with the table
302
+ structure: {table_struct}.
303
+
304
+ Note: For the time column, the data is formatted like '0.5 hour', '1 hour', '2 hours' and
305
+ so on, it tells the amount of time required to complete that specific task. So make sure
306
+ to create queries that compare just the numbers within the text. For the task_type column,
307
+ the data is either of these (Concept Understanding, Question Practice, Revision or Test)
308
+
309
+ You will also make sure multiple times that you give an SQL
310
+ Query that adheres to the given table structure, and you output just the SQL query.
311
+ Do not include anything else like new line statements, ```sql or any other text. Your output
312
+ is going to be directly fed into a Python script to extract the required information. So,
313
+ please follow all the given instructions.
314
+ Verify multiple times that the SQL query is error free for the SQLite3 format."""),
315
+ HumanMessage(content=f"""Keeping the table structure in mind: {table_struct},
316
+ Convert this prompt to an SQL query for the given table: {prompt}. Make sure your
317
+ output is just the SQL query, which can directly be used to extract required content.""")
318
+ ]
319
+ )
320
+ return response.content.strip()
321
+
322
+ def get_sql_data_for_report(sql_query):
323
+ conn = sqlite3.connect("jee_full_roadmap.db")
324
+ cursor = conn.cursor()
325
+
326
+ results = []
327
+ queries = [q.strip() for q in sql_query.strip().split(';') if q.strip()]
328
+
329
+ for query in queries:
330
+ cursor.execute(query)
331
+ columns = [desc[0] for desc in cursor.description]
332
+ rows = cursor.fetchall()
333
+ results.append({
334
+ "query": query,
335
+ "columns": columns,
336
+ "rows": rows
337
+ })
338
+ conn.close()
339
+
340
+ return results
341
+
342
+ def create_db_for_report(roadmap_data):
343
+ if not os.path.exists("jee_full_roadmap.db"):
344
  try:
345
+ conn = sqlite3.connect("jee_full_roadmap.db")
346
+ cursor = conn.cursor()
347
+
348
+ cursor.execute("DROP TABLE IF EXISTS roadmap")
349
+ cursor.execute("""
350
+ CREATE TABLE roadmap (
351
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
352
+ day_num INTEGER,
353
+ date TEXT,
354
+ subject TEXT,
355
+ chapter_name TEXT,
356
+ task_type TEXT,
357
+ time TEXT,
358
+ subtopic TEXT,
359
+ task_completed BOOLEAN,
360
+ completion_timestamp TEXT
361
+ )
362
+ """)
363
+
364
+ for day in roadmap_data["schedule"]:
365
+ date = day["date"]
366
+ day_num = day["dayNumber"]
367
+ for subj in day["subjects"]:
368
+ subject = subj["name"]
369
+ for task in subj["tasks"]:
370
+ cursor.execute("""
371
+ INSERT INTO roadmap (day_num, date, subject, chapter_name, task_type, time, subtopic, task_completed, completion_timestamp)
372
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
373
+ """, (
374
+ day_num,
375
+ date,
376
+ subject,
377
+ task["ChapterName"],
378
+ task["type"],
379
+ task["time"],
380
+ task["subtopic"],
381
+ task["task_completed"],
382
+ task["completion_timestamp"]
383
+ ))
384
+ conn.commit()
385
+ conn.close()
386
+ print("✅ Database created and data inserted successfully.")
387
  except Exception as e:
388
+ print(f"⚠️ Error initializing database: {e}")
389
+
390
+ # Function to generate report
391
+ llm = ChatOpenAI(model="gpt-4o-mini")
392
+ class Section(BaseModel):
393
+ name: str = Field(
394
+ description="Name for this section of the report.",
395
+ )
396
+ description: str = Field(
397
+ description="Brief overview of the main topics and concepts to be covered in this section.",
398
+ )
399
+ data_requirements: str = Field(
400
+ description="Description of the data needed from the roadmap database to write this section.",
401
+ )
402
+
403
+ class Sections(BaseModel):
404
+ sections: List[Section] = Field(
405
+ description="Sections of the report.",
406
+ )
407
+
408
+ planner = llm.with_structured_output(Sections)
409
+
410
+ class State(TypedDict):
411
+ sections: list[Section] # List of report sections
412
+ completed_sections: Annotated[list, operator.add] # All workers write to this key in parallel
413
+ final_report: str # Final report
414
+
415
+ # Combined helper-worker state
416
+ class ProcessorState(TypedDict):
417
+ section: Section
418
+ completed_sections: Annotated[list, operator.add]
419
+
420
+ def orchestrator(state: State):
421
+ """Orchestrator that generates a plan for the report with data requirements"""
422
+
423
+ schema = """CREATE TABLE IF NOT EXISTS roadmap (
424
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
425
+ day_num INTEGER,
426
+ date TEXT, -- [yyyy-mm-dd]
427
+ subject TEXT, -- (Physics, Chemistry or Maths)
428
+ chapter_name TEXT,
429
+ task_type TEXT, -- (Concept Understanding, Question Practice, Revision, Test)
430
+ time TEXT, -- formatted like '0.5 hour', '1 hour', '2 Hours', and so on -- Tells the amount of time required to finish the task
431
+ subtopic TEXT,
432
+ task_completed BOOLEAN, -- 0/1 indicates task completion status
433
+ completion_timestamp TEXT
434
+ )"""
435
+
436
+ # Generate queries
437
+ report_sections = planner.invoke(
438
+ [
439
+ SystemMessage(content=f"""You are responsible for creating a structured plan for a JEE preparation analysis report.
440
+
441
+ Audience: The report is intended primarily for students, but must also be insightful to mentors and parents.
442
+ Keep the language motivational and supportive, with actionable insights backed by data.
443
+
444
+ Report Format: The report will be composed of exactly 4 concise sections. Your job is to define these sections. Each section must include:
445
+ - **Name**: A short, descriptive title
446
+ - **Description**: What the section analyzes and how it helps the student
447
+ - **Data Requirements**: A plain-English description of what fields and metrics are needed from the roadmap
448
+ database whose schema is given here: {schema}
449
+
450
+ DO NOT invent new sections or formats. Use exactly the following four section templates and fill in the
451
+ descriptions and data requirements precisely.
452
+
453
+ ---
454
+
455
+ ### Study Time Analysis
456
+
457
+ **Description**: Analyze how much total time the student planned to spend vs how much they actually completed,
458
+ across different subjects and task types. This will help the student understand where their time is really going.
459
+
460
+ **Data Requirements**:
461
+ - Fields: `subject`, `task_type`, `time`, `task_completed`
462
+ - Metrics:
463
+ - Total planned time → SUM of all `time`
464
+ - Total actual time → SUM of `time` where `task_completed = 1`
465
+ - Grouped by both `subject` and `task_type`
466
+
467
+ ---
468
+
469
+ ### Task Completion Metrics
470
+
471
+ **Description**: Measure the student’s consistency and follow-through by looking at completion rates across
472
+ subjects and task types.
473
+
474
+ **Data Requirements**:
475
+ - Fields: `subject`, `task_type`, `task_completed`
476
+ - Metrics:
477
+ - Total tasks → COUNT of all tasks
478
+ - Completed tasks → COUNT of tasks where `task_completed = 1`
479
+ - Completion percentage per subject and task type
480
+
481
+ ---
482
+
483
+ ### Study Balance Analysis
484
+
485
+ **Description**: Evaluate how the student's study time is distributed across task types (e.g., Practice, Revision, Test)
486
+ within each subject. This highlights over- or under-emphasis on any category.
487
+
488
+ **Data Requirements**:
489
+ - Fields: `subject`, `task_type`, `time`
490
+ - Metrics:
491
+ - SUM of `time` for each (subject, task_type) pair where task_completed = 1
492
+ - Relative distribution of time per subject to detect imbalance
493
+
494
+ ---
495
+
496
+ ### Strengths and Areas for Improvement
497
+
498
+ **Description**:
499
+ This section analyzes how the student's effort is distributed — not by estimating how long they spent,
500
+ but by combining how many tasks they completed and how much time those completed tasks represent.
501
+ This helps identify:
502
+ - Subjects and task types where the student is showing strong commitment
503
+ - Areas that may be neglected or inconsistently approached
504
+
505
+ **Data Requirements**:
506
+ - Fields: subject, task_type, task_completed, time
507
+ - Metrics (filtered where task_completed = 1):
508
+ - Total Number of completed tasks
509
+ - Total amount of time spent
510
+ - Grouped by subject and task_type
511
+ ---
512
+
513
+ Important Constraints:
514
+ - You must include **all the mentioned fields** in the `data_requirements` — no assumptions
515
+ - Use only **aggregate metrics** — no need for per-task or per-day analysis
516
+ - Keep descriptions student-focused, clear, and motivational
517
+ - Do not alter section names or invent new ones
518
+ - Do not output anything outside the strict format above
519
+
520
+ Your output will be passed into a structured data pipeline. Return only the filled-out section definitions as described above.
521
+ """),
522
+ HumanMessage(content="""Use the given table structure of the roadmap and decide all the sections of
523
+ the report along with what should be in it and the clearly mention all the data thats required for it
524
+ from the roadmap table"""),
525
+ ]
526
+ )
527
+
528
+ return {"sections": report_sections.sections}
529
+
530
+ def processor(state: ProcessorState):
531
+ """Combined helper and worker - gets data and writes section in one step"""
532
+
533
+ section = state['section']
534
+
535
+ # HELPER PART: Get data for this section
536
+ sql_query = generate_sql_for_report(llm, section.data_requirements)
537
+ rows = get_sql_data_for_report(sql_query)
538
+ # WORKER PART: Write the section using the data
539
+ section_result = llm.invoke(
540
+ [
541
+ SystemMessage(
542
+ content=f"""Create a concise, data-driven JEE preparation report section that provides actionable insights for students,
543
+ parents, and mentors.
544
+
545
+ Requirements:
546
+ 1. Begin directly with key metrics and insights - no introductory preamble
547
+ 2. Use specific numbers, percentages, and ratios to quantify performance
548
+ 3. Include concise tables or bullet points for clarity where appropriate
549
+ 4. Highlight patterns related to:
550
+ - Task completion rates
551
+ - Time allocation efficiency
552
+ - Subject/topic focus distribution
553
+ - Study consistency patterns
554
+ 5. For each observation, provide a brief actionable recommendation focused on student improvement.
555
+ 6. Use professional but motivational tone appropriate for academic context
556
+ 7. Strictly use Markdown for formatting all the tables and the numbers
557
+ 8. Strictly keep each section very focused and write it under 0 to 50 words
558
+ 9. Verify the formatting of all the tables multiple times to ensure the markdown is correct.
559
+ 10. Check all the numbers and calculations made by you multiple times to ensure accuracy
560
+
561
+ Base all analysis strictly on the provided data - avoid assumptions beyond what's explicitly given to you.
562
+ Don't assume anything else, even a little bit.
563
+
564
+ *Important*
565
+ If you receive an empty data input, understand that the student hasn't done tasks matching the given data description. Also,
566
+ know that this report is for the student to improve themselves, and they have no part in making sure the data is logged for
567
+ this analysis. Deeply analyze the SQL query ->{sql_query} and the data description ->{section.data_requirements} used to
568
+ extract the data and figure out why there was no data available in the roadmap, which the student went through and write
569
+ the section accordingly.
570
+ """
571
+ ),
572
+ HumanMessage(
573
+ content=f"""Here is the section name: {section.name} and description: {section.description}
574
+ Data for writing this section: {rows}"""
575
+ ),
576
+ ]
577
+ )
578
+
579
+ # Return completed section
580
+ return {"completed_sections": [section_result.content]}
581
+
582
+ def synthesizer(state: State):
583
+ """Synthesize full report from sections"""
584
+
585
+ # List of completed sections
586
+ completed_sections = state["completed_sections"]
587
+
588
+ # Format completed section to str to use as context for final sections
589
+ completed_report_sections = "\n\n---\n\n".join(completed_sections)
590
+
591
+ return {"final_report": completed_report_sections}
592
+
593
+ # Assign processors function
594
+ def assign_processors(state: State):
595
+ """Assign a processor to each section in the plan"""
596
+ return [Send("processor", {"section": s}) for s in state["sections"]]
597
+
598
+ def generate_report(full_roadmap):
599
+ with st.spinner("Generating performance report using AI..."):
600
+ # Build workflow
601
+ workflow_builder = StateGraph(State)
602
+
603
+ # Add the nodes
604
+ workflow_builder.add_node("orchestrator", orchestrator)
605
+ workflow_builder.add_node("processor", processor)
606
+ workflow_builder.add_node("synthesizer", synthesizer)
607
+
608
+ # Add edges to connect nodes
609
+ workflow_builder.add_edge(START, "orchestrator")
610
+ workflow_builder.add_conditional_edges("orchestrator", assign_processors, ["processor"])
611
+ workflow_builder.add_edge("processor", "synthesizer")
612
+ workflow_builder.add_edge("synthesizer", END)
613
+
614
+ # Compile the workflow
615
+ workflow = workflow_builder.compile()
616
+
617
+ # Initialize database
618
+ create_db_for_report(full_roadmap)
619
+
620
+ # Invoke
621
+ state = workflow.invoke({})
622
+
623
+ st.session_state.final_report = state["final_report"]
624
 
625
  # Function to extract available dates
626
  def extract_available_dates():
 
650
  with st.spinner("Optimizing task distribution using evaluator-optimizer approach..."):
651
  try:
652
  # Initialize needed components
653
+ llm = ChatOpenAI(model="gpt-4o-mini", api_key = os.getenv("OPENAI_API_KEY"))
654
 
655
  # Schema for structured output to use in evaluation
656
  class Feedback(BaseModel):
 
1004
  elif page == "Task Analysis":
1005
  st.title("📊 Task Analysis")
1006
 
1007
+ choice = st.selectbox("Choose the roadmap to use for building report", ["Four Day Roadmap", "Full Roadmap"])
1008
+ if choice == "Four Day Roadmap":
1009
+ if st.session_state.data is None:
1010
+ st.warning("Please load roadmap data first from the Home page.")
1011
+ st.session_state.report_data = st.session_state.data
1012
+ elif choice == "Full Roadmap":
1013
+ with open("synthesized_full_roadmap.json", "r") as f:
1014
+ st.session_state.report_data = json.load(f)
1015
+
1016
+ st.markdown("### Performance Report")
1017
+
1018
+ if st.button("🔍 Generate Performance Report"):
1019
+ generate_report(st.session_state.report_data)
1020
+
1021
+ if st.session_state.final_report:
1022
+ st.markdown(st.session_state.final_report)
1023
  else:
1024
+ st.info("Click the button above to generate your performance report.")
1025
+
1026
+ # Add visualization options
1027
+ if st.session_state.data:
1028
+ st.subheader("Task Breakdown")
 
 
 
 
1029
 
1030
+ # Simple task statistics
1031
+ if st.checkbox("Show Task Statistics"):
1032
+ task_count = 0
1033
+ subject_counts = {}
1034
+ type_counts = {}
1035
 
1036
+ for day in st.session_state.report_data["schedule"]:
1037
+ for subject in day["subjects"]:
1038
+ subject_name = subject["name"]
1039
+ if subject_name not in subject_counts:
1040
+ subject_counts[subject_name] = 0
1041
+
1042
+ for task in subject["tasks"]:
1043
+ subject_counts[subject_name] += 1
1044
+ task_count += 1
 
 
1045
 
1046
+ # Count by task type
1047
+ task_type = task.get("type", "Unknown")
1048
+ if task_type not in type_counts:
1049
+ type_counts[task_type] = 0
1050
+ type_counts[task_type] += 1
1051
+
1052
+ st.write(f"Total tasks: {task_count}")
1053
+
1054
+ # Create charts for data visualization
1055
+ col1, col2 = st.columns(2)
1056
+
1057
+ with col1:
1058
+ st.subheader("Subject Distribution")
1059
+ st.bar_chart(subject_counts)
1060
+
1061
+ with col2:
1062
+ st.subheader("Task Type Distribution")
1063
+ st.bar_chart(type_counts)
 
 
 
 
1064
  # ---- ROADMAP CHATBOT PAGE ----
1065
  elif page == "Roadmap Chatbot":
1066
  st.title("🤖 Roadmap Chatbot Assistant")