Spaces:
Sleeping
Sleeping
gauravlochab
commited on
Commit
·
cb9360a
1
Parent(s):
6879e5a
feat: implement logging for error handling in APR data processing
Browse files- apr_visualization.py +26 -22
apr_visualization.py
CHANGED
|
@@ -11,6 +11,10 @@ import requests
|
|
| 11 |
import sys
|
| 12 |
import json
|
| 13 |
from typing import List, Dict, Any
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
# Global variable to store the data for reuse
|
| 16 |
global_df = None
|
|
@@ -22,7 +26,7 @@ def get_agent_type_by_name(type_name: str) -> Dict[str, Any]:
|
|
| 22 |
"""Get agent type by name"""
|
| 23 |
response = requests.get(f"{API_BASE_URL}/api/agent-types/name/{type_name}")
|
| 24 |
if response.status_code == 404:
|
| 25 |
-
|
| 26 |
return None
|
| 27 |
response.raise_for_status()
|
| 28 |
return response.json()
|
|
@@ -31,7 +35,7 @@ def get_attribute_definition_by_name(attr_name: str) -> Dict[str, Any]:
|
|
| 31 |
"""Get attribute definition by name"""
|
| 32 |
response = requests.get(f"{API_BASE_URL}/api/attributes/name/{attr_name}")
|
| 33 |
if response.status_code == 404:
|
| 34 |
-
|
| 35 |
return None
|
| 36 |
response.raise_for_status()
|
| 37 |
return response.json()
|
|
@@ -40,7 +44,7 @@ def get_agents_by_type(type_id: int) -> List[Dict[str, Any]]:
|
|
| 40 |
"""Get all agents of a specific type"""
|
| 41 |
response = requests.get(f"{API_BASE_URL}/api/agent-types/{type_id}/agents/")
|
| 42 |
if response.status_code == 404:
|
| 43 |
-
|
| 44 |
return []
|
| 45 |
response.raise_for_status()
|
| 46 |
return response.json()
|
|
@@ -56,7 +60,7 @@ def get_attribute_values_by_type_and_attr(agents: List[Dict[str, Any]], attr_def
|
|
| 56 |
# Call the /api/agents/{agent_id}/attributes/ endpoint
|
| 57 |
response = requests.get(f"{API_BASE_URL}/api/agents/{agent_id}/attributes/", params={"limit": 1000})
|
| 58 |
if response.status_code == 404:
|
| 59 |
-
|
| 60 |
continue
|
| 61 |
|
| 62 |
try:
|
|
@@ -67,7 +71,7 @@ def get_attribute_values_by_type_and_attr(agents: List[Dict[str, Any]], attr_def
|
|
| 67 |
filtered_attrs = [attr for attr in agent_attrs if attr.get("attr_def_id") == attr_def_id]
|
| 68 |
all_attributes.extend(filtered_attrs)
|
| 69 |
except requests.exceptions.RequestException as e:
|
| 70 |
-
|
| 71 |
|
| 72 |
return all_attributes
|
| 73 |
|
|
@@ -101,7 +105,7 @@ def extract_apr_value(attr: Dict[str, Any]) -> Dict[str, Any]:
|
|
| 101 |
|
| 102 |
return {"apr": apr, "timestamp": timestamp_dt, "agent_id": attr["agent_id"], "is_dummy": False}
|
| 103 |
except (json.JSONDecodeError, KeyError, TypeError) as e:
|
| 104 |
-
|
| 105 |
return {"apr": None, "timestamp": None, "agent_id": attr["agent_id"], "is_dummy": False}
|
| 106 |
|
| 107 |
def fetch_apr_data_from_db():
|
|
@@ -114,7 +118,7 @@ def fetch_apr_data_from_db():
|
|
| 114 |
# Step 1: Find the Modius agent type
|
| 115 |
modius_type = get_agent_type_by_name("Modius")
|
| 116 |
if not modius_type:
|
| 117 |
-
|
| 118 |
global_df = pd.DataFrame([])
|
| 119 |
return global_df
|
| 120 |
|
|
@@ -123,7 +127,7 @@ def fetch_apr_data_from_db():
|
|
| 123 |
# Step 2: Find the APR attribute definition
|
| 124 |
apr_attr_def = get_attribute_definition_by_name("APR")
|
| 125 |
if not apr_attr_def:
|
| 126 |
-
|
| 127 |
global_df = pd.DataFrame([])
|
| 128 |
return global_df
|
| 129 |
|
|
@@ -132,14 +136,14 @@ def fetch_apr_data_from_db():
|
|
| 132 |
# Step 3: Get all agents of type Modius
|
| 133 |
modius_agents = get_agents_by_type(type_id)
|
| 134 |
if not modius_agents:
|
| 135 |
-
|
| 136 |
global_df = pd.DataFrame([])
|
| 137 |
return global_df
|
| 138 |
|
| 139 |
# Step 4: Fetch all APR values for Modius agents
|
| 140 |
apr_attributes = get_attribute_values_by_type_and_attr(modius_agents, attr_def_id)
|
| 141 |
if not apr_attributes:
|
| 142 |
-
|
| 143 |
global_df = pd.DataFrame([])
|
| 144 |
return global_df
|
| 145 |
|
|
@@ -165,7 +169,7 @@ def fetch_apr_data_from_db():
|
|
| 165 |
|
| 166 |
# Convert list of dictionaries to DataFrame
|
| 167 |
if not apr_data_list:
|
| 168 |
-
|
| 169 |
global_df = pd.DataFrame([])
|
| 170 |
return global_df
|
| 171 |
|
|
@@ -173,11 +177,11 @@ def fetch_apr_data_from_db():
|
|
| 173 |
return global_df
|
| 174 |
|
| 175 |
except requests.exceptions.RequestException as e:
|
| 176 |
-
|
| 177 |
global_df = pd.DataFrame([])
|
| 178 |
return global_df
|
| 179 |
except Exception as e:
|
| 180 |
-
|
| 181 |
global_df = pd.DataFrame([])
|
| 182 |
return global_df
|
| 183 |
|
|
@@ -190,7 +194,7 @@ def generate_apr_visualizations():
|
|
| 190 |
|
| 191 |
# If we got no data at all, return placeholder figures
|
| 192 |
if df.empty:
|
| 193 |
-
|
| 194 |
# Create empty visualizations with a message using Plotly
|
| 195 |
fig = go.Figure()
|
| 196 |
fig.add_annotation(
|
|
@@ -234,7 +238,7 @@ def create_time_series_graph_per_agent(df):
|
|
| 234 |
unique_agents = df['agent_id'].unique()
|
| 235 |
|
| 236 |
if len(unique_agents) == 0:
|
| 237 |
-
|
| 238 |
fig = go.Figure()
|
| 239 |
fig.add_annotation(
|
| 240 |
text="No agent data available",
|
|
@@ -357,7 +361,7 @@ def create_time_series_graph_per_agent(df):
|
|
| 357 |
img_file = "modius_apr_per_agent_graph.png"
|
| 358 |
fig.write_image(img_file)
|
| 359 |
|
| 360 |
-
|
| 361 |
|
| 362 |
# Return the figure object for direct use in Gradio
|
| 363 |
return fig
|
|
@@ -365,7 +369,7 @@ def create_time_series_graph_per_agent(df):
|
|
| 365 |
def create_combined_time_series_graph(df):
|
| 366 |
"""Create a combined time series graph for all agents using Plotly"""
|
| 367 |
if len(df) == 0:
|
| 368 |
-
|
| 369 |
fig = go.Figure()
|
| 370 |
fig.add_annotation(
|
| 371 |
text="No data available",
|
|
@@ -501,7 +505,7 @@ def create_combined_time_series_graph(df):
|
|
| 501 |
img_file = "modius_apr_combined_graph.png"
|
| 502 |
fig.write_image(img_file)
|
| 503 |
|
| 504 |
-
|
| 505 |
|
| 506 |
# Return the figure object for direct use in Gradio
|
| 507 |
return fig
|
|
@@ -509,7 +513,7 @@ def create_combined_time_series_graph(df):
|
|
| 509 |
def save_to_csv(df):
|
| 510 |
"""Save the APR data DataFrame to a CSV file and return the file path"""
|
| 511 |
if df.empty:
|
| 512 |
-
|
| 513 |
return None
|
| 514 |
|
| 515 |
# Define the CSV file path
|
|
@@ -517,13 +521,13 @@ def save_to_csv(df):
|
|
| 517 |
|
| 518 |
# Save to CSV
|
| 519 |
df.to_csv(csv_file, index=False)
|
| 520 |
-
|
| 521 |
|
| 522 |
# Also generate a statistics CSV file
|
| 523 |
stats_df = generate_statistics_from_data(df)
|
| 524 |
stats_csv = "modius_apr_statistics.csv"
|
| 525 |
stats_df.to_csv(stats_csv, index=False)
|
| 526 |
-
|
| 527 |
|
| 528 |
return csv_file
|
| 529 |
|
|
@@ -585,4 +589,4 @@ def generate_statistics_from_data(df):
|
|
| 585 |
}
|
| 586 |
stats_list.append(overall_stats)
|
| 587 |
|
| 588 |
-
return pd.DataFrame(stats_list)
|
|
|
|
| 11 |
import sys
|
| 12 |
import json
|
| 13 |
from typing import List, Dict, Any
|
| 14 |
+
import logging
|
| 15 |
+
|
| 16 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
|
| 19 |
# Global variable to store the data for reuse
|
| 20 |
global_df = None
|
|
|
|
| 26 |
"""Get agent type by name"""
|
| 27 |
response = requests.get(f"{API_BASE_URL}/api/agent-types/name/{type_name}")
|
| 28 |
if response.status_code == 404:
|
| 29 |
+
logger.error(f"Agent type '{type_name}' not found")
|
| 30 |
return None
|
| 31 |
response.raise_for_status()
|
| 32 |
return response.json()
|
|
|
|
| 35 |
"""Get attribute definition by name"""
|
| 36 |
response = requests.get(f"{API_BASE_URL}/api/attributes/name/{attr_name}")
|
| 37 |
if response.status_code == 404:
|
| 38 |
+
logger.error(f"Attribute definition '{attr_name}' not found")
|
| 39 |
return None
|
| 40 |
response.raise_for_status()
|
| 41 |
return response.json()
|
|
|
|
| 44 |
"""Get all agents of a specific type"""
|
| 45 |
response = requests.get(f"{API_BASE_URL}/api/agent-types/{type_id}/agents/")
|
| 46 |
if response.status_code == 404:
|
| 47 |
+
logger.error(f"No agents found for type ID {type_id}")
|
| 48 |
return []
|
| 49 |
response.raise_for_status()
|
| 50 |
return response.json()
|
|
|
|
| 60 |
# Call the /api/agents/{agent_id}/attributes/ endpoint
|
| 61 |
response = requests.get(f"{API_BASE_URL}/api/agents/{agent_id}/attributes/", params={"limit": 1000})
|
| 62 |
if response.status_code == 404:
|
| 63 |
+
logger.error(f"No attributes found for agent ID {agent_id}")
|
| 64 |
continue
|
| 65 |
|
| 66 |
try:
|
|
|
|
| 71 |
filtered_attrs = [attr for attr in agent_attrs if attr.get("attr_def_id") == attr_def_id]
|
| 72 |
all_attributes.extend(filtered_attrs)
|
| 73 |
except requests.exceptions.RequestException as e:
|
| 74 |
+
logger.error(f"Error fetching attributes for agent ID {agent_id}: {e}")
|
| 75 |
|
| 76 |
return all_attributes
|
| 77 |
|
|
|
|
| 105 |
|
| 106 |
return {"apr": apr, "timestamp": timestamp_dt, "agent_id": attr["agent_id"], "is_dummy": False}
|
| 107 |
except (json.JSONDecodeError, KeyError, TypeError) as e:
|
| 108 |
+
logger.error(f"Error parsing JSON value: {e} for agent_id: {attr.get('agent_id')}")
|
| 109 |
return {"apr": None, "timestamp": None, "agent_id": attr["agent_id"], "is_dummy": False}
|
| 110 |
|
| 111 |
def fetch_apr_data_from_db():
|
|
|
|
| 118 |
# Step 1: Find the Modius agent type
|
| 119 |
modius_type = get_agent_type_by_name("Modius")
|
| 120 |
if not modius_type:
|
| 121 |
+
logger.error("Modius agent type not found, using placeholder data")
|
| 122 |
global_df = pd.DataFrame([])
|
| 123 |
return global_df
|
| 124 |
|
|
|
|
| 127 |
# Step 2: Find the APR attribute definition
|
| 128 |
apr_attr_def = get_attribute_definition_by_name("APR")
|
| 129 |
if not apr_attr_def:
|
| 130 |
+
logger.error("APR attribute definition not found, using placeholder data")
|
| 131 |
global_df = pd.DataFrame([])
|
| 132 |
return global_df
|
| 133 |
|
|
|
|
| 136 |
# Step 3: Get all agents of type Modius
|
| 137 |
modius_agents = get_agents_by_type(type_id)
|
| 138 |
if not modius_agents:
|
| 139 |
+
logger.error("No agents of type 'Modius' found")
|
| 140 |
global_df = pd.DataFrame([])
|
| 141 |
return global_df
|
| 142 |
|
| 143 |
# Step 4: Fetch all APR values for Modius agents
|
| 144 |
apr_attributes = get_attribute_values_by_type_and_attr(modius_agents, attr_def_id)
|
| 145 |
if not apr_attributes:
|
| 146 |
+
logger.error("No APR values found for 'Modius' agents")
|
| 147 |
global_df = pd.DataFrame([])
|
| 148 |
return global_df
|
| 149 |
|
|
|
|
| 169 |
|
| 170 |
# Convert list of dictionaries to DataFrame
|
| 171 |
if not apr_data_list:
|
| 172 |
+
logger.error("No valid APR data extracted")
|
| 173 |
global_df = pd.DataFrame([])
|
| 174 |
return global_df
|
| 175 |
|
|
|
|
| 177 |
return global_df
|
| 178 |
|
| 179 |
except requests.exceptions.RequestException as e:
|
| 180 |
+
logger.error(f"API request error: {e}")
|
| 181 |
global_df = pd.DataFrame([])
|
| 182 |
return global_df
|
| 183 |
except Exception as e:
|
| 184 |
+
logger.error(f"Error fetching APR data: {e}")
|
| 185 |
global_df = pd.DataFrame([])
|
| 186 |
return global_df
|
| 187 |
|
|
|
|
| 194 |
|
| 195 |
# If we got no data at all, return placeholder figures
|
| 196 |
if df.empty:
|
| 197 |
+
logger.info("No APR data available. Using fallback visualization.")
|
| 198 |
# Create empty visualizations with a message using Plotly
|
| 199 |
fig = go.Figure()
|
| 200 |
fig.add_annotation(
|
|
|
|
| 238 |
unique_agents = df['agent_id'].unique()
|
| 239 |
|
| 240 |
if len(unique_agents) == 0:
|
| 241 |
+
logger.error("No agent data to plot")
|
| 242 |
fig = go.Figure()
|
| 243 |
fig.add_annotation(
|
| 244 |
text="No agent data available",
|
|
|
|
| 361 |
img_file = "modius_apr_per_agent_graph.png"
|
| 362 |
fig.write_image(img_file)
|
| 363 |
|
| 364 |
+
logger.info(f"Per-agent graph saved to {graph_file} and {img_file}")
|
| 365 |
|
| 366 |
# Return the figure object for direct use in Gradio
|
| 367 |
return fig
|
|
|
|
| 369 |
def create_combined_time_series_graph(df):
|
| 370 |
"""Create a combined time series graph for all agents using Plotly"""
|
| 371 |
if len(df) == 0:
|
| 372 |
+
logger.error("No data to plot combined graph")
|
| 373 |
fig = go.Figure()
|
| 374 |
fig.add_annotation(
|
| 375 |
text="No data available",
|
|
|
|
| 505 |
img_file = "modius_apr_combined_graph.png"
|
| 506 |
fig.write_image(img_file)
|
| 507 |
|
| 508 |
+
logger.info(f"Combined graph saved to {graph_file} and {img_file}")
|
| 509 |
|
| 510 |
# Return the figure object for direct use in Gradio
|
| 511 |
return fig
|
|
|
|
| 513 |
def save_to_csv(df):
|
| 514 |
"""Save the APR data DataFrame to a CSV file and return the file path"""
|
| 515 |
if df.empty:
|
| 516 |
+
logger.error("No APR data to save to CSV")
|
| 517 |
return None
|
| 518 |
|
| 519 |
# Define the CSV file path
|
|
|
|
| 521 |
|
| 522 |
# Save to CSV
|
| 523 |
df.to_csv(csv_file, index=False)
|
| 524 |
+
logger.info(f"APR data saved to {csv_file}")
|
| 525 |
|
| 526 |
# Also generate a statistics CSV file
|
| 527 |
stats_df = generate_statistics_from_data(df)
|
| 528 |
stats_csv = "modius_apr_statistics.csv"
|
| 529 |
stats_df.to_csv(stats_csv, index=False)
|
| 530 |
+
logger.info(f"Statistics saved to {stats_csv}")
|
| 531 |
|
| 532 |
return csv_file
|
| 533 |
|
|
|
|
| 589 |
}
|
| 590 |
stats_list.append(overall_stats)
|
| 591 |
|
| 592 |
+
return pd.DataFrame(stats_list)
|