Skip to content

Commit c440779

Browse files
hystsgradio-pr-bot
andauthored
Close matplotlib figures after rendering them in gr.Plot (#13522)
* Close matplotlib figures after rendering in gr.Plot Figures returned to gr.Plot were never closed after being encoded, so every plot update left another open figure in pyplot's global registry. Long-running apps leaked memory and eventually hit matplotlib's "More than 20 figures have been opened" warning. Close the figure in Plot.postprocess once it has been encoded. Only Figure instances are closed; the legacy path where a handler returns the pyplot module itself is left untouched. savefig still works on a closed figure, so apps that keep a figure around and return it repeatedly are unaffected (covered by a test). Fixes #11701 * add changeset * Only close Figure instances, use png in equality test Address Copilot review comments: guard plt.close() with an isinstance check against matplotlib.figure.Figure so non-Figure matplotlib objects cannot raise TypeError, and force png format in test_postprocess_accepts_closed_figure so the byte-equality assertion does not depend on webp encoder stability. * Close figure in finally without importing pyplot Per Copilot review: postprocess can run at component init outside MatplotlibBackendMananger, so look up an already-imported pyplot via sys.modules instead of importing it (a figure can only be in the registry if pyplot was imported), and close in a finally block so the figure is cleaned up even if encoding fails. * Guard Figure import behind pyplot presence check Per Copilot review: only import matplotlib.figure inside the finally block after confirming pyplot is already in sys.modules, so the cleanup can never raise and mask an encoding error. * Assert figure registry is empty after postprocess Per Copilot review: close pre-existing figures first and assert plt.get_fignums() is empty instead of checking a single figure number, making the regression test slightly stronger. * Use try/except ImportError idiom, hoist test imports Address abidlabs's review comments: replace the sys.modules lookup with the codebase's usual try-import/except-ImportError pattern, and move the matplotlib import to the top of the test file. * Return early when matplotlib import fails Address abidlabs's review comment: replace the pass in the ImportError branch with an early return of the encoded PlotData, dropping the try/finally so the guard-clause return is safe. --------- Co-authored-by: gradio-pr-bot <[email protected]>
1 parent 2d6eb2a commit c440779

3 files changed

Lines changed: 37 additions & 0 deletions

File tree

‎.changeset/great-dogs-carry.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"gradio": patch
3+
---
4+
5+
fix:Close matplotlib figures after rendering them in `gr.Plot`

‎gradio/components/plot.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,13 @@ def postprocess(self, value: Any) -> PlotData | None:
143143
if isinstance(value, ModuleType) or "matplotlib" in value.__module__:
144144
dtype = "matplotlib"
145145
out_y = processing_utils.encode_plot_to_base64(value, self.format)
146+
try:
147+
import matplotlib.pyplot as plt
148+
from matplotlib.figure import Figure
149+
except ImportError:
150+
return PlotData(type=dtype, plot=out_y)
151+
if isinstance(value, Figure):
152+
plt.close(value)
146153
elif "bokeh" in value.__module__:
147154
dtype = "bokeh"
148155
from bokeh.embed import json_item # type: ignore

‎test/components/test_plot.py‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import matplotlib.pyplot as plt
12
import pytest
23

34
import gradio as gr
@@ -58,6 +59,30 @@ def test_postprocess_altair(self):
5859
assert isinstance(out["plot"], str)
5960
assert out["plot"] == chart.to_json()
6061

62+
def test_postprocess_closes_matplotlib_figure(self):
63+
"""
64+
postprocess
65+
"""
66+
with utils.MatplotlibBackendMananger():
67+
plt.close("all")
68+
component = gr.Plot()
69+
fig = plt.figure()
70+
plt.plot([1, 2, 3], [1, 2, 3])
71+
component.postprocess(fig)
72+
assert not plt.get_fignums()
73+
74+
def test_postprocess_accepts_closed_figure(self):
75+
"""
76+
postprocess
77+
"""
78+
with utils.MatplotlibBackendMananger():
79+
component = gr.Plot(format="png")
80+
fig = plt.figure()
81+
plt.plot([1, 2, 3], [1, 2, 3])
82+
first = component.postprocess(fig)
83+
second = component.postprocess(fig)
84+
assert first and second and first.plot == second.plot
85+
6186
def test_plot_format_parameter(self):
6287
"""
6388
postprocess

0 commit comments

Comments
 (0)