GuglielmoTor commited on
Commit
fed5558
·
verified ·
1 Parent(s): ddc6277

Update run_agentic_pipeline.py

Browse files
Files changed (1) hide show
  1. run_agentic_pipeline.py +49 -67
run_agentic_pipeline.py CHANGED
@@ -1,11 +1,13 @@
1
  import gradio as gr
2
  import pandas as pd
3
- import json
4
  import logging
5
  from typing import Dict, Any, List, Optional
6
 
7
- # Assuming these functions are in ui.insights_ui_generator
8
- # Make sure to have this file updated with the new `format_report_for_display` function
 
 
 
9
  try:
10
  from ui.insights_ui_generator import (
11
  format_report_for_display,
@@ -20,50 +22,31 @@ except ImportError as e:
20
  def extract_key_results_for_selection(okrs_dict): return []
21
  def format_single_okr_for_display(okr_data, **kwargs): return "Agentic modules not loaded. OKR display unavailable."
22
 
23
-
24
  logger = logging.getLogger(__name__)
25
 
26
- def load_and_display_agentic_results(
27
- token_state: dict,
28
- orchestration_raw_results_st: Optional[dict],
29
- selected_key_result_ids_st: List[str],
30
- key_results_for_selection_st: List[dict]
31
- ):
32
  """
33
  Loads pre-computed agentic results from the state, populates the report library dropdown,
34
- and displays the latest report and its associated OKRs by default.
35
 
36
- This function is designed to work with the UI defined in app.py and expects a specific
37
- order of outputs.
38
 
39
  Args:
40
  token_state: The main state dictionary containing the bubble_agentic_analysis_data DataFrame.
41
- orchestration_raw_results_st: The state holding the raw JSON/dict of the currently displayed report.
42
- selected_key_result_ids_st: The state for the IDs of selected Key Results.
43
- key_results_for_selection_st: The state holding the list of all available Key Results for selection.
44
 
45
  Returns:
46
  A tuple of Gradio updates matching the `agentic_display_outputs` list in `app.py`.
47
  """
48
- # Default empty/initial return values that match the output components list
49
- # The order is critical:
50
- # 1. agentic_report_display_md
51
- # 2. report_selector_dd
52
- # 3. key_results_cbg
53
- # 4. okr_detail_display_md
54
- # 5. orchestration_raw_results_st
55
- # 6. selected_key_result_ids_st
56
- # 7. key_results_for_selection_st
57
- # 8. agentic_pipeline_status_md
58
  initial_updates = (
59
- "No agentic analysis data found in Bubble.",
60
- gr.update(choices=[], value=None, interactive=False),
61
- gr.update(choices=[], value=[], interactive=False),
62
- "No OKRs to display.",
63
- None,
64
- [],
65
- [],
66
- "Status: No agentic analysis data found."
67
  )
68
 
69
  if not AGENTIC_MODULES_LOADED:
@@ -82,11 +65,9 @@ def load_and_display_agentic_results(
82
  if 'Created Date' not in agentic_df.columns or '_id' not in agentic_df.columns:
83
  raise KeyError("Required columns ('Created Date', '_id') not found in agentic data.")
84
 
85
- # Ensure 'Created Date' is datetime, then sort to get the latest report first
86
  agentic_df['Created Date'] = pd.to_datetime(agentic_df['Created Date'])
87
  agentic_df = agentic_df.sort_values(by='Created Date', ascending=False).reset_index(drop=True)
88
 
89
- # Create choices for the dropdown: (Display Name, Unique ID)
90
  report_choices = [
91
  (f"{row.get('report_type', 'Report')} - {row['Created Date'].strftime('%Y-%m-%d %H:%M')}", row['_id'])
92
  for _, row in agentic_df.iterrows()
@@ -95,56 +76,57 @@ def load_and_display_agentic_results(
95
  if not report_choices:
96
  return initial_updates
97
 
98
- # --- 2. Load and Display the Latest Report by Default ---
99
  latest_report_series = agentic_df.iloc[0]
100
  latest_report_id = latest_report_series['_id']
101
 
102
- # Format the latest report's content for the Markdown display
103
  report_display_md = format_report_for_display(latest_report_series)
104
 
105
- # Create the update for the report library dropdown
106
  report_selector_update = gr.update(choices=report_choices, value=latest_report_id, interactive=True)
107
 
108
- # --- 3. Load and Prepare OKRs from the Latest Report ---
109
  raw_results_state = None
110
  okr_details_md = "No OKRs found in the latest report."
111
  key_results_cbg_update = gr.update(choices=[], value=[], interactive=False)
112
  all_krs_state = []
113
 
114
- # Assumption: The full JSON from the agent is stored in 'orchestration_results'.
115
- if 'orchestration_results' in latest_report_series and pd.notna(latest_report_series['orchestration_results']):
116
- try:
117
- raw_results_state = json.loads(latest_report_series['orchestration_results'])
118
- except json.JSONDecodeError:
119
- logger.error(f"Failed to parse 'orchestration_results' JSON for report ID {latest_report_id}")
120
- raw_results_state = {} # Avoid crashing, proceed with empty data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  else:
122
- raw_results_state = {}
 
123
 
124
- actionable_okrs_dict = raw_results_state.get("actionable_okrs", {})
125
-
126
- if actionable_okrs_dict:
127
- all_krs_state = extract_key_results_for_selection(actionable_okrs_dict)
128
- if all_krs_state:
129
- kr_choices = [(kr['kr_description'], kr['unique_kr_id']) for kr in all_krs_state]
130
- key_results_cbg_update = gr.update(choices=kr_choices, value=[], interactive=True)
131
-
132
- # Format all OKRs for initial display
133
- okrs_list = actionable_okrs_dict.get("okrs", [])
134
- output_md_parts = [
135
- format_single_okr_for_display(okr_data, okr_main_index=okr_idx)
136
- for okr_idx, okr_data in enumerate(okrs_list)
137
- ]
138
- okr_details_md = "\n\n---\n\n".join(output_md_parts) if output_md_parts else okr_details_md
139
 
140
  status_update = f"Status: Loaded {len(agentic_df)} reports. Displaying the latest from {latest_report_series['Created Date'].strftime('%Y-%m-%d')}."
141
 
 
142
  return (
143
- report_display_md,
144
  report_selector_update,
145
- key_results_cbg_update,
146
- okr_details_md,
147
- raw_results_state,
148
  [], # Reset selected KRs
149
  all_krs_state,
150
  status_update
 
1
  import gradio as gr
2
  import pandas as pd
 
3
  import logging
4
  from typing import Dict, Any, List, Optional
5
 
6
+ # --- MODIFIED: Import the reconstruction function ---
7
+ # This function is now central to fetching the detailed OKR data.
8
+ from services.report_data_handler import fetch_and_reconstruct_data_from_bubble
9
+
10
+ # UI formatting functions
11
  try:
12
  from ui.insights_ui_generator import (
13
  format_report_for_display,
 
22
  def extract_key_results_for_selection(okrs_dict): return []
23
  def format_single_okr_for_display(okr_data, **kwargs): return "Agentic modules not loaded. OKR display unavailable."
24
 
 
25
  logger = logging.getLogger(__name__)
26
 
27
+ def load_and_display_agentic_results(token_state: dict):
 
 
 
 
 
28
  """
29
  Loads pre-computed agentic results from the state, populates the report library dropdown,
30
+ and displays the LATEST report and its fully reconstructed OKRs by default.
31
 
32
+ This function is called on the initial application load.
 
33
 
34
  Args:
35
  token_state: The main state dictionary containing the bubble_agentic_analysis_data DataFrame.
 
 
 
36
 
37
  Returns:
38
  A tuple of Gradio updates matching the `agentic_display_outputs` list in `app.py`.
39
  """
40
+ # Default empty/initial return values that match the output components list. The order is critical.
 
 
 
 
 
 
 
 
 
41
  initial_updates = (
42
+ "No agentic analysis data found in Bubble.", # 1. agentic_report_display_md
43
+ gr.update(choices=[], value=None, interactive=False), # 2. report_selector_dd
44
+ gr.update(choices=[], value=[], interactive=False), # 3. key_results_cbg
45
+ "No OKRs to display.", # 4. okr_detail_display_md
46
+ None, # 5. orchestration_raw_results_st
47
+ [], # 6. selected_key_result_ids_st
48
+ [], # 7. key_results_for_selection_st
49
+ "Status: No agentic analysis data found." # 8. agentic_pipeline_status_md
50
  )
51
 
52
  if not AGENTIC_MODULES_LOADED:
 
65
  if 'Created Date' not in agentic_df.columns or '_id' not in agentic_df.columns:
66
  raise KeyError("Required columns ('Created Date', '_id') not found in agentic data.")
67
 
 
68
  agentic_df['Created Date'] = pd.to_datetime(agentic_df['Created Date'])
69
  agentic_df = agentic_df.sort_values(by='Created Date', ascending=False).reset_index(drop=True)
70
 
 
71
  report_choices = [
72
  (f"{row.get('report_type', 'Report')} - {row['Created Date'].strftime('%Y-%m-%d %H:%M')}", row['_id'])
73
  for _, row in agentic_df.iterrows()
 
76
  if not report_choices:
77
  return initial_updates
78
 
79
+ # --- 2. Process the Latest Report by Default ---
80
  latest_report_series = agentic_df.iloc[0]
81
  latest_report_id = latest_report_series['_id']
82
 
83
+ # Format the main report text for display
84
  report_display_md = format_report_for_display(latest_report_series)
85
 
86
+ # Update the report library dropdown and select the latest one
87
  report_selector_update = gr.update(choices=report_choices, value=latest_report_id, interactive=True)
88
 
89
+ # --- 3. MODIFIED: Fetch, Reconstruct, and Prepare OKRs from the Latest Report ---
90
  raw_results_state = None
91
  okr_details_md = "No OKRs found in the latest report."
92
  key_results_cbg_update = gr.update(choices=[], value=[], interactive=False)
93
  all_krs_state = []
94
 
95
+ # Call the key function to get all linked data (OKRs, KRs, Tasks) from Bubble
96
+ reconstructed_data = fetch_and_reconstruct_data_from_bubble(latest_report_series)
97
+
98
+ if reconstructed_data:
99
+ raw_results_state = reconstructed_data
100
+ actionable_okrs_dict = raw_results_state.get("actionable_okrs", {})
101
+
102
+ if actionable_okrs_dict:
103
+ all_krs_state = extract_key_results_for_selection(actionable_okrs_dict)
104
+ if all_krs_state:
105
+ # Populate the Key Results checkbox group
106
+ kr_choices = [(kr['kr_description'], kr['unique_kr_id']) for kr in all_krs_state]
107
+ key_results_cbg_update = gr.update(choices=kr_choices, value=[], interactive=True)
108
+
109
+ # Format all OKRs for the initial detailed display
110
+ okrs_list = actionable_okrs_dict.get("okrs", [])
111
+ output_md_parts = [
112
+ format_single_okr_for_display(okr_data, okr_main_index=okr_idx)
113
+ for okr_idx, okr_data in enumerate(okrs_list)
114
+ ]
115
+ okr_details_md = "\n\n---\n\n".join(output_md_parts) if output_md_parts else okr_details_md
116
  else:
117
+ logger.error(f"Failed to reconstruct full data for latest report ID {latest_report_id}")
118
+ okr_details_md = "Error: Could not reconstruct OKR data for this report."
119
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
 
121
  status_update = f"Status: Loaded {len(agentic_df)} reports. Displaying the latest from {latest_report_series['Created Date'].strftime('%Y-%m-%d')}."
122
 
123
+ # --- 4. Return all UI and State Updates ---
124
  return (
125
+ report_display_md,
126
  report_selector_update,
127
+ key_results_cbg_update,
128
+ okr_details_md,
129
+ raw_results_state, # This is now the fully reconstructed dictionary
130
  [], # Reset selected KRs
131
  all_krs_state,
132
  status_update