mgbam commited on
Commit
de6f1e8
Β·
verified Β·
1 Parent(s): 9538f35

Update tools/plot_generator.py

Browse files
Files changed (1) hide show
  1. tools/plot_generator.py +19 -23
tools/plot_generator.py CHANGED
@@ -1,7 +1,9 @@
 
1
  import os
2
  import tempfile
3
  import pandas as pd
4
  import plotly.graph_objects as go
 
5
 
6
 
7
  def plot_metric_tool(
@@ -12,30 +14,28 @@ def plot_metric_tool(
12
  title: str = None,
13
  line_width: int = 2,
14
  marker_size: int = 6
15
- ):
16
  """
17
- Load CSV or Excel file, parse a time series metric, and return an interactive Plotly Figure.
18
- Also saves a high-resolution PNG to a temp directory for static embedding.
19
 
20
  Returns:
21
- fig (go.Figure) or error string starting with '❌'.
 
22
  """
23
- # 0) Load data
24
  ext = os.path.splitext(file_path)[1].lower()
25
  try:
26
- if ext in ('.xls', '.xlsx'):
27
- df = pd.read_excel(file_path)
28
- else:
29
- df = pd.read_csv(file_path)
30
  except Exception as exc:
31
  return f"❌ Failed to load file: {exc}"
32
 
33
- # 1) Validate columns
34
  missing = [c for c in (date_col, value_col) if c not in df.columns]
35
  if missing:
36
  return f"❌ Missing column(s): {', '.join(missing)}"
37
 
38
- # 2) Parse date and ensure numeric values
39
  try:
40
  df[date_col] = pd.to_datetime(df[date_col], errors='coerce')
41
  except Exception:
@@ -45,7 +45,7 @@ def plot_metric_tool(
45
  if df.empty:
46
  return f"❌ No valid data after cleaning '{date_col}'/'{value_col}'"
47
 
48
- # 3) Sort and aggregate duplicates
49
  df = (
50
  df[[date_col, value_col]]
51
  .groupby(date_col, as_index=True)
@@ -53,7 +53,7 @@ def plot_metric_tool(
53
  .sort_index()
54
  )
55
 
56
- # 4) Create Plotly figure
57
  fig = go.Figure(
58
  data=[
59
  go.Scatter(
@@ -62,30 +62,26 @@ def plot_metric_tool(
62
  mode='lines+markers',
63
  line=dict(width=line_width),
64
  marker=dict(size=marker_size),
65
- name=value_col
66
  )
67
  ]
68
  )
69
- plot_title = title or f"{value_col} Trend"
70
  fig.update_layout(
71
- title=plot_title,
72
  xaxis_title=date_col,
73
  yaxis_title=value_col,
74
  template='plotly_dark',
75
  hovermode='x unified'
76
  )
77
 
78
- # 5) Save static PNG
79
  os.makedirs(output_dir, exist_ok=True)
80
- tmpfile = tempfile.NamedTemporaryFile(
81
- suffix='.png', prefix='trend_', dir=output_dir, delete=False
82
- )
83
- img_path = tmpfile.name
84
- tmpfile.close()
85
  try:
86
  fig.write_image(img_path, scale=2)
87
  except Exception as exc:
88
  return f"❌ Failed saving image: {exc}"
89
 
90
- # 6) Return figure and path for embedding
91
  return fig, img_path
 
1
+ # tools/plot_generator.py
2
  import os
3
  import tempfile
4
  import pandas as pd
5
  import plotly.graph_objects as go
6
+ from typing import Tuple, Union
7
 
8
 
9
  def plot_metric_tool(
 
14
  title: str = None,
15
  line_width: int = 2,
16
  marker_size: int = 6
17
+ ) -> Union[Tuple[go.Figure, str], str]:
18
  """
19
+ Load CSV or Excel file, parse a time series metric, and return an interactive Plotly Figure
20
+ plus a high-res PNG file path for static embedding.
21
 
22
  Returns:
23
+ - (fig, img_path) on success
24
+ - error string starting with '❌' on failure
25
  """
26
+ # Load data
27
  ext = os.path.splitext(file_path)[1].lower()
28
  try:
29
+ df = pd.read_excel(file_path) if ext in ('.xls', '.xlsx') else pd.read_csv(file_path)
 
 
 
30
  except Exception as exc:
31
  return f"❌ Failed to load file: {exc}"
32
 
33
+ # Validate columns
34
  missing = [c for c in (date_col, value_col) if c not in df.columns]
35
  if missing:
36
  return f"❌ Missing column(s): {', '.join(missing)}"
37
 
38
+ # Parse and clean
39
  try:
40
  df[date_col] = pd.to_datetime(df[date_col], errors='coerce')
41
  except Exception:
 
45
  if df.empty:
46
  return f"❌ No valid data after cleaning '{date_col}'/'{value_col}'"
47
 
48
+ # Aggregate duplicates and sort
49
  df = (
50
  df[[date_col, value_col]]
51
  .groupby(date_col, as_index=True)
 
53
  .sort_index()
54
  )
55
 
56
+ # Build figure
57
  fig = go.Figure(
58
  data=[
59
  go.Scatter(
 
62
  mode='lines+markers',
63
  line=dict(width=line_width),
64
  marker=dict(size=marker_size),
65
+ name=value_col,
66
  )
67
  ]
68
  )
 
69
  fig.update_layout(
70
+ title=title or f"{value_col} Trend",
71
  xaxis_title=date_col,
72
  yaxis_title=value_col,
73
  template='plotly_dark',
74
  hovermode='x unified'
75
  )
76
 
77
+ # Save PNG
78
  os.makedirs(output_dir, exist_ok=True)
79
+ tmp = tempfile.NamedTemporaryFile(suffix='.png', prefix='trend_', dir=output_dir, delete=False)
80
+ img_path = tmp.name
81
+ tmp.close()
 
 
82
  try:
83
  fig.write_image(img_path, scale=2)
84
  except Exception as exc:
85
  return f"❌ Failed saving image: {exc}"
86
 
 
87
  return fig, img_path