guohanghui commited on
Commit
bb9e754
·
verified ·
1 Parent(s): 156dce3

Update pyfolio/mcp_output/mcp_plugin/mcp_service.py

Browse files
pyfolio/mcp_output/mcp_plugin/mcp_service.py CHANGED
@@ -38,34 +38,41 @@ from pyfolio.plotting import (
38
  mcp = FastMCP("pyfolio_service")
39
 
40
  def _save_plot_as_base64(plt, plot_name):
41
- """Save plot as base64 string and to file"""
42
  from io import BytesIO
43
 
44
  # Generate timestamp for unique filename
45
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
46
  filename = f"{plot_name}_{timestamp}.png"
47
 
48
- # Save to current working directory instead of /tmp
49
- current_dir = os.getcwd()
50
- filepath = os.path.join(current_dir, filename)
51
-
52
- # Save to file
53
- plt.savefig(filepath, dpi=300, bbox_inches='tight')
 
 
 
 
 
54
 
55
- # Convert to base64
56
  buffer = BytesIO()
57
  plt.savefig(buffer, format='png', dpi=300, bbox_inches='tight')
58
  buffer.seek(0)
59
- image_base64 = base64.b64encode(buffer.getvalue()).decode('utf-8')
 
60
  buffer.close()
61
 
62
- # Create data URI
63
  data_uri = f"data:image/png;base64,{image_base64}"
64
 
65
  return {
66
  "image_base64": image_base64,
67
  "image_path": filepath,
68
- "data_uri": data_uri
 
69
  }
70
 
71
  def _convert_to_series(data: List[float], name: str = "returns") -> pd.Series:
 
38
  mcp = FastMCP("pyfolio_service")
39
 
40
  def _save_plot_as_base64(plt, plot_name):
41
+ """Save plot as base64 string for HuggingFace deployment"""
42
  from io import BytesIO
43
 
44
  # Generate timestamp for unique filename
45
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
46
  filename = f"{plot_name}_{timestamp}.png"
47
 
48
+ # For HuggingFace deployment, we primarily return base64 data
49
+ # Try to save to a temporary location if possible
50
+ try:
51
+ # Try to save to /tmp or current directory
52
+ import tempfile
53
+ temp_dir = tempfile.gettempdir()
54
+ filepath = f"{temp_dir}/{filename}"
55
+ plt.savefig(filepath, dpi=300, bbox_inches='tight')
56
+ except Exception as e:
57
+ # If file saving fails, we still have the base64 data
58
+ filepath = f"Unable to save file: {str(e)}"
59
 
60
+ # Convert to base64 (this is the main output for HuggingFace)
61
  buffer = BytesIO()
62
  plt.savefig(buffer, format='png', dpi=300, bbox_inches='tight')
63
  buffer.seek(0)
64
+ image_base64_bytes = base64.b64encode(buffer.getvalue())
65
+ image_base64 = image_base64_bytes.decode('utf-8')
66
  buffer.close()
67
 
68
+ # Create data URI for direct display
69
  data_uri = f"data:image/png;base64,{image_base64}"
70
 
71
  return {
72
  "image_base64": image_base64,
73
  "image_path": filepath,
74
+ "data_uri": data_uri,
75
+ "filename": filename
76
  }
77
 
78
  def _convert_to_series(data: List[float], name: str = "returns") -> pd.Series: