GuglielmoTor commited on
Commit
6faec7c
·
verified ·
1 Parent(s): 6b39ad4

Update run_agentic_pipeline.py

Browse files
Files changed (1) hide show
  1. run_agentic_pipeline.py +29 -57
run_agentic_pipeline.py CHANGED
@@ -3,8 +3,7 @@ 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
@@ -18,35 +17,31 @@ try:
18
  except ImportError as e:
19
  logging.error(f"Could not import agentic pipeline display modules: {e}. Tabs 3 and 4 will be disabled.")
20
  AGENTIC_MODULES_LOADED = False
21
- def format_report_for_display(report_data): return "Agentic modules not loaded. Report unavailable."
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:
@@ -57,79 +52,56 @@ def load_and_display_agentic_results(token_state: dict):
57
  agentic_df = token_state.get("bubble_agentic_analysis_data")
58
 
59
  if agentic_df is None or agentic_df.empty:
60
- logger.warning("Agentic analysis DataFrame is missing or empty in the state.")
61
  return initial_updates
62
 
63
  try:
64
- # --- 1. Prepare Report Library ---
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()
74
- ]
75
 
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
133
  )
134
 
135
  except Exception as e:
 
3
  import logging
4
  from typing import Dict, Any, List, Optional
5
 
6
+ # Import the reconstruction function that now expects a cache dictionary
 
7
  from services.report_data_handler import fetch_and_reconstruct_data_from_bubble
8
 
9
  # UI formatting functions
 
17
  except ImportError as e:
18
  logging.error(f"Could not import agentic pipeline display modules: {e}. Tabs 3 and 4 will be disabled.")
19
  AGENTIC_MODULES_LOADED = False
20
+ def format_report_for_display(report_data): return "Agentic modules not loaded."
21
  def extract_key_results_for_selection(okrs_dict): return []
22
+ def format_single_okr_for_display(okr_data, **kwargs): return "Agentic modules not loaded."
23
 
24
  logger = logging.getLogger(__name__)
25
 
26
+ def load_and_display_agentic_results(token_state: dict, session_cache: dict):
27
  """
28
+ Loads agentic results from state, populates the report library, and displays
29
+ the LATEST report and its fully reconstructed OKRs by default, using a session-specific cache.
 
 
30
 
31
  Args:
32
+ token_state: The main state dictionary with Bubble data.
33
+ session_cache: The session-specific cache for reconstructed data.
34
 
35
  Returns:
36
+ A tuple of Gradio updates, including the updated cache.
37
  """
 
38
  initial_updates = (
39
+ "No agentic analysis data found in Bubble.",
40
+ gr.update(choices=[], value=None, interactive=False),
41
+ gr.update(choices=[], value=[], interactive=False),
42
+ "No OKRs to display.",
43
+ None, [], [], "Status: No agentic analysis data found.",
44
+ session_cache # Return the cache unchanged
 
 
45
  )
46
 
47
  if not AGENTIC_MODULES_LOADED:
 
52
  agentic_df = token_state.get("bubble_agentic_analysis_data")
53
 
54
  if agentic_df is None or agentic_df.empty:
55
+ logger.warning("Agentic analysis DataFrame is missing or empty.")
56
  return initial_updates
57
 
58
  try:
 
59
  if 'Created Date' not in agentic_df.columns or '_id' not in agentic_df.columns:
60
+ raise KeyError("Required columns ('Created Date', '_id') not found.")
61
 
62
  agentic_df['Created Date'] = pd.to_datetime(agentic_df['Created Date'])
63
  agentic_df = agentic_df.sort_values(by='Created Date', ascending=False).reset_index(drop=True)
64
 
65
+ report_choices = [(f"{row.get('report_type', 'Report')} - {row['Created Date'].strftime('%Y-%m-%d %H:%M')}", row['_id'])
66
+ for _, row in agentic_df.iterrows()]
 
 
67
 
68
  if not report_choices:
69
  return initial_updates
70
 
 
71
  latest_report_series = agentic_df.iloc[0]
72
  latest_report_id = latest_report_series['_id']
73
 
 
74
  report_display_md = format_report_for_display(latest_report_series)
 
 
75
  report_selector_update = gr.update(choices=report_choices, value=latest_report_id, interactive=True)
76
 
77
+ # --- MODIFIED: Use the session cache for data reconstruction ---
78
+ reconstructed_data, updated_cache = fetch_and_reconstruct_data_from_bubble(latest_report_series, session_cache)
79
+
80
+ raw_results_state, okr_details_md = None, "No OKRs found in the latest report."
81
  key_results_cbg_update = gr.update(choices=[], value=[], interactive=False)
82
  all_krs_state = []
83
 
 
 
 
84
  if reconstructed_data:
85
  raw_results_state = reconstructed_data
86
  actionable_okrs_dict = raw_results_state.get("actionable_okrs", {})
 
87
  if actionable_okrs_dict:
88
  all_krs_state = extract_key_results_for_selection(actionable_okrs_dict)
89
  if all_krs_state:
 
90
  kr_choices = [(kr['kr_description'], kr['unique_kr_id']) for kr in all_krs_state]
91
  key_results_cbg_update = gr.update(choices=kr_choices, value=[], interactive=True)
 
 
92
  okrs_list = actionable_okrs_dict.get("okrs", [])
93
+ output_md_parts = [format_single_okr_for_display(okr, okr_main_index=i) for i, okr in enumerate(okrs_list)]
 
 
 
94
  okr_details_md = "\n\n---\n\n".join(output_md_parts) if output_md_parts else okr_details_md
95
  else:
96
+ logger.error(f"Failed to reconstruct data for latest report ID {latest_report_id}")
97
  okr_details_md = "Error: Could not reconstruct OKR data for this report."
98
 
99
+ status_update = f"Status: Loaded {len(agentic_df)} reports. Displaying latest from {latest_report_series['Created Date'].strftime('%Y-%m-%d')}."
 
100
 
 
101
  return (
102
+ report_display_md, report_selector_update, key_results_cbg_update,
103
+ okr_details_md, raw_results_state, [], all_krs_state, status_update,
104
+ updated_cache # Return the potentially updated cache
 
 
 
 
 
105
  )
106
 
107
  except Exception as e: