Jeremy Live commited on
Commit
d5a1ba3
·
1 Parent(s): 1974ab3

show graph

Browse files
Files changed (1) hide show
  1. app.py +26 -30
app.py CHANGED
@@ -238,34 +238,30 @@ def safe_get_column(df, column):
238
  # If still not found, raise a helpful error
239
  raise KeyError(f"Column '{column}' not found in DataFrame. Available columns: {list(df.columns)}")
240
 
241
- def plot_and_save(plt, filename=None, **savefig_kwargs):
242
- import os
243
- import matplotlib
244
-
245
- # Make sure we're using the non-interactive backend
246
- matplotlib.use('Agg')
247
-
248
- if filename is None:
249
- filename = PLOT_FILENAME
250
-
251
- # Convert to absolute path
252
- filename = os.path.abspath(str(filename))
253
-
254
- # Ensure the directory exists
255
- os.makedirs(os.path.dirname(filename) or '.', exist_ok=True)
256
-
257
  try:
258
- # Set default savefig parameters if not provided
259
- save_params = {'bbox_inches': 'tight', 'dpi': 100}
260
- save_params.update(savefig_kwargs)
 
 
 
 
261
 
262
- # Save the plot using the matplotlib savefig function directly
263
- plt.savefig(filename, **save_params)
 
264
  plt.close()
265
- print(f"[DEBUG] Plot saved to: {filename}")
266
- return filename
 
 
 
 
 
 
267
  except Exception as e:
268
- print(f"[ERROR] Failed to save plot: {str(e)}")
269
  return None
270
 
271
  # Monkey patch DataFrame to add safe column access
@@ -287,16 +283,16 @@ pd.DataFrame.safe_get = safe_get_column
287
  script_content = script_content.replace("['Close']", ".safe_get('close')")
288
  script_content = script_content.replace("['close']", ".safe_get('close')")
289
 
290
- # Replace plt.savefig() calls with our helper
291
  script_content = re.sub(
292
- r'plt\.savefig\(([^)]+)\)',
293
- r'plot_and_save(plt, \1)',
294
  script_content
295
  )
296
 
297
- # If no savefig call is found, add one at the end of the script
298
- if 'plt.savefig(' not in script_content and 'plot_and_save(' not in script_content:
299
- script_content += "\n# Ensure plot is saved\nif 'plt' in locals() and len(plt.get_fignums()) > 0:\n plot_and_save(plt, PLOT_FILENAME)\n"
300
 
301
  # Write the updated script back
302
  with open(temp_script_path, 'w') as f:
 
238
  # If still not found, raise a helpful error
239
  raise KeyError(f"Column '{column}' not found in DataFrame. Available columns: {list(df.columns)}")
240
 
241
+ def show_plot(plt):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
  try:
243
+ # Use a non-interactive backend to avoid GUI issues
244
+ import matplotlib
245
+ matplotlib.use('Agg')
246
+
247
+ # Create a temporary file to store the plot
248
+ import io
249
+ import base64
250
 
251
+ # Save plot to a bytes buffer
252
+ buf = io.BytesIO()
253
+ plt.savefig(buf, format='png', bbox_inches='tight', dpi=100)
254
  plt.close()
255
+
256
+ # Convert to base64 for display
257
+ buf.seek(0)
258
+ img_str = base64.b64encode(buf.read()).decode('utf-8')
259
+ buf.close()
260
+
261
+ # Return HTML to display the image
262
+ return f'<img src="data:image/png;base64,{img_str}" />'
263
  except Exception as e:
264
+ print(f"[ERROR] Failed to display plot: {str(e)}")
265
  return None
266
 
267
  # Monkey patch DataFrame to add safe column access
 
283
  script_content = script_content.replace("['Close']", ".safe_get('close')")
284
  script_content = script_content.replace("['close']", ".safe_get('close')")
285
 
286
+ # Replace plt.show() calls with our helper
287
  script_content = re.sub(
288
+ r'plt\\.show\\(\s*\\)',
289
+ r'print(show_plot(plt))',
290
  script_content
291
  )
292
 
293
+ # If no show() call is found, add one at the end of the script
294
+ if 'plt.show()' not in script_content:
295
+ script_content += "\n# Display the plot if any figures exist\nif 'plt' in locals() and len(plt.get_fignums()) > 0:\n print(show_plot(plt))\n"
296
 
297
  # Write the updated script back
298
  with open(temp_script_path, 'w') as f: