Hari-Prasath-M91 commited on
Commit
a466cac
·
verified ·
1 Parent(s): bdb093e

Enhanced the Chatbot and Updated the Report Generation

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