We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
find_requirements includes datetime and random
I'm on the current `main` branch of Panel.

When I use `find_requirements` like below I get "packages" included like `datetime` and `random` from the `stdlib`.

```python
from panel.io.convert import find_requirements
code = """
import panel as pn
import pandas as pd

import random
from datetime import datetime, timedelta
"""

requirements = find_requirements(code)
print(requirements)
```

```bash
$ python app.py
['datetime', 'pandas', 'panel', 'random']
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `panel/io/mime_render.py`
Content:
```
1 """
2 Utilities for executing Python code and rendering the resulting output
3 using a similar MIME-type based rendering system as implemented by
4 IPython.
5 
6 Attempts to limit the actual MIME types that have to be rendered on
7 to a minimum simplifying frontend implementation:
8 
9     - application/bokeh: Model JSON representation
10     - text/plain: HTML escaped string output
11     - text/html: HTML code to insert into the DOM
12 """
13 
14 from __future__ import annotations
15 
16 import ast
17 import base64
18 import copy
19 import io
20 import pathlib
21 import pkgutil
22 import sys
23 import traceback
24 
25 from contextlib import redirect_stderr, redirect_stdout
26 from html import escape
27 from textwrap import dedent
28 from typing import Any, Dict, List
29 
30 import markdown
31 
32 #---------------------------------------------------------------------
33 # Import API
34 #---------------------------------------------------------------------
35 
36 def _stdlibs():
37     env_dir = str(pathlib.Path(sys.executable).parent.parent)
38     modules = list(sys.builtin_module_names)
39     for m in pkgutil.iter_modules():
40         mpath = getattr(m.module_finder, 'path', '')
41         if mpath.startswith(env_dir) and 'site-packages' not in mpath:
42             modules.append(m.name)
43     return modules
44 
45 _STDLIBS = _stdlibs()
46 _PACKAGE_MAP = {
47     'sklearn': 'scikit-learn',
48     'transformers_js': 'transformers-js-py',
49 }
50 _IGNORED_PKGS = ['js', 'pyodide']
51 _PANDAS_AUTODETECT = ['bokeh.sampledata', 'as_frame']
52 
53 def find_requirements(code: str) -> List[str]:
54     """
55     Finds the packages required in a string of code.
56 
57     Parameters
58     ----------
59     code : str
60        the Python code to run.
61 
62     Returns
63     -------
64     ``List[str]``
65         A list of package names that are to be installed for the code to be able to run.
66 
67     Examples
68     --------
69     >>> code = "import numpy as np; import scipy.stats"
70     >>> find_imports(code)
71     ['numpy', 'scipy']
72     """
73     # handle mis-indented input from multi-line strings
74     code = dedent(code)
75 
76     mod = ast.parse(code)
77     imports = set()
78     for node in ast.walk(mod):
79         if isinstance(node, ast.Import):
80             for name in node.names:
81                 node_name = name.name
82                 imports.add(node_name.split(".")[0])
83         elif isinstance(node, ast.ImportFrom):
84             module_name = node.module
85             if module_name is None:
86                 continue
87             imports.add(module_name.split(".")[0])
88 
89     packages = []
90     for pkg in sorted(imports):
91         pkg = _PACKAGE_MAP.get(pkg, pkg)
92         if pkg in _STDLIBS:
93             continue
94         elif isinstance(pkg, list):
95             packages.extend(pkg)
96         else:
97             packages.append(pkg)
98     if any(pdd in code for pdd in _PANDAS_AUTODETECT) and 'pandas' not in packages:
99         packages.append('pandas')
100     return [pkg for pkg in packages if pkg not in _IGNORED_PKGS]
101 
102 #---------------------------------------------------------------------
103 # Execution API
104 #---------------------------------------------------------------------
105 
106 class WriteCallbackStream(io.StringIO):
107 
108     def __init__(self, on_write=None, escape=True):
109         self._onwrite = on_write
110         self._escape = escape
111         super().__init__()
112 
113     def write(self, s):
114         if self._onwrite:
115             self._onwrite(escape(s) if self._escape else s)
116         super().write(s)
117 
118 def _convert_expr(expr: ast.Expr) -> ast.Expression:
119     """
120     Converts an ast.Expr to and ast.Expression that can be compiled
121     and evaled.
122     """
123     expr.lineno = 0
124     expr.col_offset = 0
125     return ast.Expression(expr.value, lineno=0, col_offset = 0)
126 
127 _OUT_BUFFER = []
128 
129 def _display(*objs, **kwargs):
130     """
131     IPython.display compatibility wrapper.
132 
133     Note: This only handles a single display.
134     """
135     _OUT_BUFFER.extend(list(objs))
136 
137 def exec_with_return(
138     code: str,
139     global_context: Dict[str, Any] = None,
140     stdout: Any = None,
141     stderr: Any = None
142 ) -> Any:
143     """
144     Executes a code snippet and returns the resulting output of the
145     last line.
146 
147     Arguments
148     ---------
149     code: str
150         The code to execute
151     global_context: Dict[str, Any]
152         The globals to inject into the execution context.
153     stdout: io.StringIO
154         The stream to redirect stdout to.
155     stderr: io.StringIO
156         The stream to redirect stderr to.
157 
158     Returns
159     -------
160 
161     The return value of the executed code.
162     """
163     global_context = global_context if global_context else globals()
164     global_context['display'] = _display
165     code_ast = ast.parse(code)
166 
167     init_ast = copy.deepcopy(code_ast)
168     init_ast.body = code_ast.body[:-1]
169 
170     last_ast = copy.deepcopy(code_ast)
171     last_ast.body = code_ast.body[-1:]
172 
173     stdout = stdout or sys.stdout
174     stderr = stderr or sys.stderr
175     with redirect_stdout(stdout), redirect_stderr(stderr):
176         try:
177             exec(compile(init_ast, "<ast>", "exec"), global_context)
178             if not last_ast.body:
179                 out = None
180             elif type(last_ast.body[0]) == ast.Expr:
181                 out = eval(compile(_convert_expr(last_ast.body[0]), "<ast>", "eval"), global_context)
182             else:
183                 exec(compile(last_ast, "<ast>", "exec"), global_context)
184                 out = None
185             if code.strip().endswith(';'):
186                 out = None
187             if _OUT_BUFFER and out is None:
188                 out = _OUT_BUFFER[-1]
189         except Exception:
190             out = None
191             traceback.print_exc(file=stderr)
192         finally:
193             _OUT_BUFFER.clear()
194     return out
195 
196 #---------------------------------------------------------------------
197 # MIME Render API
198 #---------------------------------------------------------------------
199 
200 MIME_METHODS = {
201     "__repr__": "text/plain",
202     "_repr_html_": "text/html",
203     "_repr_markdown_": "text/markdown",
204     "_repr_svg_": "image/svg+xml",
205     "_repr_png_": "image/png",
206     "_repr_pdf_": "application/pdf",
207     "_repr_jpeg_": "image/jpeg",
208     "_repr_latex": "text/latex",
209     "_repr_json_": "application/json",
210     "_repr_javascript_": "application/javascript",
211     "savefig": "image/png",
212     "to_html": "text/html"
213 }
214 
215 # Rendering function
216 
217 def render_svg(value, meta, mime):
218     return value, 'text/html'
219 
220 def render_image(value, meta, mime):
221     data = f"data:{mime};charset=utf-8;base64,{value}"
222     attrs = " ".join(['{k}="{v}"' for k, v in meta.items()])
223     return f'<img src="{data}" {attrs}</img>', 'text/html'
224 
225 def render_javascript(value, meta, mime):
226     return f'<script>{value}</script>', 'text/html'
227 
228 def render_markdown(value, meta, mime):
229     return (markdown.markdown(
230         value, extensions=["extra", "smarty", "codehilite"], output_format='html5'
231     ), 'text/html')
232 
233 def render_pdf(value, meta, mime):
234     data = value.encode('utf-8')
235     base64_pdf = base64.b64encode(data).decode("utf-8")
236     src = f"data:application/pdf;base64,{base64_pdf}"
237     return f'<embed src="{src}" width="100%" height="100%" type="application/pdf">', 'text/html'
238 
239 def identity(value, meta, mime):
240     return value, mime
241 
242 MIME_RENDERERS = {
243     "image/png": render_image,
244     "image/jpeg": render_image,
245     "image/svg+xml": identity,
246     "application/json": identity,
247     "application/javascript": render_javascript,
248     "application/pdf": render_pdf,
249     "text/html": identity,
250     "text/markdown": render_markdown,
251     "text/plain": identity,
252 }
253 
254 def eval_formatter(obj, print_method):
255     """
256     Evaluates a formatter method.
257     """
258     if print_method == "__repr__":
259         return repr(obj)
260     elif hasattr(obj, print_method):
261         if print_method == "savefig":
262             buf = io.BytesIO()
263             obj.savefig(buf, format="png")
264             buf.seek(0)
265             return base64.b64encode(buf.read()).decode("utf-8")
266         return getattr(obj, print_method)()
267     elif print_method == "_repr_mimebundle_":
268         return {}, {}
269     return None
270 
271 def format_mime(obj):
272     """
273     Formats object using _repr_x_ methods.
274     """
275     if isinstance(obj, str):
276         return escape(obj), "text/plain"
277     mimebundle = eval_formatter(obj, "_repr_mimebundle_")
278     if isinstance(mimebundle, tuple):
279         format_dict, _ = mimebundle
280     else:
281         format_dict = mimebundle
282 
283     output, not_available = None, []
284     for method, mime_type in reversed(list(MIME_METHODS.items())):
285         if mime_type in format_dict:
286             output = format_dict[mime_type]
287         elif isinstance(obj, type) and method != '__repr__':
288             output = None
289         else:
290             output = eval_formatter(obj, method)
291 
292         if output is None:
293             continue
294         elif mime_type not in MIME_RENDERERS:
295             not_available.append(mime_type)
296             continue
297         break
298     if output is None:
299         output = repr(output)
300         mime_type = "text/plain"
301     elif isinstance(output, tuple):
302         output, meta = output
303     else:
304         meta = {}
305     content, mime_type = MIME_RENDERERS[mime_type](output, meta, mime_type)
306     if mime_type == 'text/plain':
307         content = escape(content)
308     return content, mime_type
309
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/panel/io/mime_render.py b/panel/io/mime_render.py
--- a/panel/io/mime_render.py
+++ b/panel/io/mime_render.py
@@ -34,6 +34,8 @@
 #---------------------------------------------------------------------
 
 def _stdlibs():
+    if sys.version_info[:2] >= (3, 10):
+        return sys.stdlib_module_names
     env_dir = str(pathlib.Path(sys.executable).parent.parent)
     modules = list(sys.builtin_module_names)
     for m in pkgutil.iter_modules():

{"golden_diff": "diff --git a/panel/io/mime_render.py b/panel/io/mime_render.py\n--- a/panel/io/mime_render.py\n+++ b/panel/io/mime_render.py\n@@ -34,6 +34,8 @@\n #---------------------------------------------------------------------\n \n def _stdlibs():\n+    if sys.version_info[:2] >= (3, 10):\n+        return sys.stdlib_module_names\n     env_dir = str(pathlib.Path(sys.executable).parent.parent)\n     modules = list(sys.builtin_module_names)\n     for m in pkgutil.iter_modules():\n", "issue": "find_requirements includes datetime and random\nI'm on the current `main` branch of Panel.\r\n\r\nWhen I use `find_requirements` like below I get \"packages\" included like `datetime` and `random` from the `stdlib`.\r\n\r\n```python\r\nfrom panel.io.convert import find_requirements\r\ncode = \"\"\"\r\nimport panel as pn\r\nimport pandas as pd\r\n\r\nimport random\r\nfrom datetime import datetime, timedelta\r\n\"\"\"\r\n\r\nrequirements = find_requirements(code)\r\nprint(requirements)\r\n```\r\n\r\n```bash\r\n$ python app.py\r\n['datetime', 'pandas', 'panel', 'random']\r\n```\n", "before_files": [{"content": "\"\"\"\nUtilities for executing Python code and rendering the resulting output\nusing a similar MIME-type based rendering system as implemented by\nIPython.\n\nAttempts to limit the actual MIME types that have to be rendered on\nto a minimum simplifying frontend implementation:\n\n    - application/bokeh: Model JSON representation\n    - text/plain: HTML escaped string output\n    - text/html: HTML code to insert into the DOM\n\"\"\"\n\nfrom __future__ import annotations\n\nimport ast\nimport base64\nimport copy\nimport io\nimport pathlib\nimport pkgutil\nimport sys\nimport traceback\n\nfrom contextlib import redirect_stderr, redirect_stdout\nfrom html import escape\nfrom textwrap import dedent\nfrom typing import Any, Dict, List\n\nimport markdown\n\n#---------------------------------------------------------------------\n# Import API\n#---------------------------------------------------------------------\n\ndef _stdlibs():\n    env_dir = str(pathlib.Path(sys.executable).parent.parent)\n    modules = list(sys.builtin_module_names)\n    for m in pkgutil.iter_modules():\n        mpath = getattr(m.module_finder, 'path', '')\n        if mpath.startswith(env_dir) and 'site-packages' not in mpath:\n            modules.append(m.name)\n    return modules\n\n_STDLIBS = _stdlibs()\n_PACKAGE_MAP = {\n    'sklearn': 'scikit-learn',\n    'transformers_js': 'transformers-js-py',\n}\n_IGNORED_PKGS = ['js', 'pyodide']\n_PANDAS_AUTODETECT = ['bokeh.sampledata', 'as_frame']\n\ndef find_requirements(code: str) -> List[str]:\n    \"\"\"\n    Finds the packages required in a string of code.\n\n    Parameters\n    ----------\n    code : str\n       the Python code to run.\n\n    Returns\n    -------\n    ``List[str]``\n        A list of package names that are to be installed for the code to be able to run.\n\n    Examples\n    --------\n    >>> code = \"import numpy as np; import scipy.stats\"\n    >>> find_imports(code)\n    ['numpy', 'scipy']\n    \"\"\"\n    # handle mis-indented input from multi-line strings\n    code = dedent(code)\n\n    mod = ast.parse(code)\n    imports = set()\n    for node in ast.walk(mod):\n        if isinstance(node, ast.Import):\n            for name in node.names:\n                node_name = name.name\n                imports.add(node_name.split(\".\")[0])\n        elif isinstance(node, ast.ImportFrom):\n            module_name = node.module\n            if module_name is None:\n                continue\n            imports.add(module_name.split(\".\")[0])\n\n    packages = []\n    for pkg in sorted(imports):\n        pkg = _PACKAGE_MAP.get(pkg, pkg)\n        if pkg in _STDLIBS:\n            continue\n        elif isinstance(pkg, list):\n            packages.extend(pkg)\n        else:\n            packages.append(pkg)\n    if any(pdd in code for pdd in _PANDAS_AUTODETECT) and 'pandas' not in packages:\n        packages.append('pandas')\n    return [pkg for pkg in packages if pkg not in _IGNORED_PKGS]\n\n#---------------------------------------------------------------------\n# Execution API\n#---------------------------------------------------------------------\n\nclass WriteCallbackStream(io.StringIO):\n\n    def __init__(self, on_write=None, escape=True):\n        self._onwrite = on_write\n        self._escape = escape\n        super().__init__()\n\n    def write(self, s):\n        if self._onwrite:\n            self._onwrite(escape(s) if self._escape else s)\n        super().write(s)\n\ndef _convert_expr(expr: ast.Expr) -> ast.Expression:\n    \"\"\"\n    Converts an ast.Expr to and ast.Expression that can be compiled\n    and evaled.\n    \"\"\"\n    expr.lineno = 0\n    expr.col_offset = 0\n    return ast.Expression(expr.value, lineno=0, col_offset = 0)\n\n_OUT_BUFFER = []\n\ndef _display(*objs, **kwargs):\n    \"\"\"\n    IPython.display compatibility wrapper.\n\n    Note: This only handles a single display.\n    \"\"\"\n    _OUT_BUFFER.extend(list(objs))\n\ndef exec_with_return(\n    code: str,\n    global_context: Dict[str, Any] = None,\n    stdout: Any = None,\n    stderr: Any = None\n) -> Any:\n    \"\"\"\n    Executes a code snippet and returns the resulting output of the\n    last line.\n\n    Arguments\n    ---------\n    code: str\n        The code to execute\n    global_context: Dict[str, Any]\n        The globals to inject into the execution context.\n    stdout: io.StringIO\n        The stream to redirect stdout to.\n    stderr: io.StringIO\n        The stream to redirect stderr to.\n\n    Returns\n    -------\n\n    The return value of the executed code.\n    \"\"\"\n    global_context = global_context if global_context else globals()\n    global_context['display'] = _display\n    code_ast = ast.parse(code)\n\n    init_ast = copy.deepcopy(code_ast)\n    init_ast.body = code_ast.body[:-1]\n\n    last_ast = copy.deepcopy(code_ast)\n    last_ast.body = code_ast.body[-1:]\n\n    stdout = stdout or sys.stdout\n    stderr = stderr or sys.stderr\n    with redirect_stdout(stdout), redirect_stderr(stderr):\n        try:\n            exec(compile(init_ast, \"<ast>\", \"exec\"), global_context)\n            if not last_ast.body:\n                out = None\n            elif type(last_ast.body[0]) == ast.Expr:\n                out = eval(compile(_convert_expr(last_ast.body[0]), \"<ast>\", \"eval\"), global_context)\n            else:\n                exec(compile(last_ast, \"<ast>\", \"exec\"), global_context)\n                out = None\n            if code.strip().endswith(';'):\n                out = None\n            if _OUT_BUFFER and out is None:\n                out = _OUT_BUFFER[-1]\n        except Exception:\n            out = None\n            traceback.print_exc(file=stderr)\n        finally:\n            _OUT_BUFFER.clear()\n    return out\n\n#---------------------------------------------------------------------\n# MIME Render API\n#---------------------------------------------------------------------\n\nMIME_METHODS = {\n    \"__repr__\": \"text/plain\",\n    \"_repr_html_\": \"text/html\",\n    \"_repr_markdown_\": \"text/markdown\",\n    \"_repr_svg_\": \"image/svg+xml\",\n    \"_repr_png_\": \"image/png\",\n    \"_repr_pdf_\": \"application/pdf\",\n    \"_repr_jpeg_\": \"image/jpeg\",\n    \"_repr_latex\": \"text/latex\",\n    \"_repr_json_\": \"application/json\",\n    \"_repr_javascript_\": \"application/javascript\",\n    \"savefig\": \"image/png\",\n    \"to_html\": \"text/html\"\n}\n\n# Rendering function\n\ndef render_svg(value, meta, mime):\n    return value, 'text/html'\n\ndef render_image(value, meta, mime):\n    data = f\"data:{mime};charset=utf-8;base64,{value}\"\n    attrs = \" \".join(['{k}=\"{v}\"' for k, v in meta.items()])\n    return f'<img src=\"{data}\" {attrs}</img>', 'text/html'\n\ndef render_javascript(value, meta, mime):\n    return f'<script>{value}</script>', 'text/html'\n\ndef render_markdown(value, meta, mime):\n    return (markdown.markdown(\n        value, extensions=[\"extra\", \"smarty\", \"codehilite\"], output_format='html5'\n    ), 'text/html')\n\ndef render_pdf(value, meta, mime):\n    data = value.encode('utf-8')\n    base64_pdf = base64.b64encode(data).decode(\"utf-8\")\n    src = f\"data:application/pdf;base64,{base64_pdf}\"\n    return f'<embed src=\"{src}\" width=\"100%\" height=\"100%\" type=\"application/pdf\">', 'text/html'\n\ndef identity(value, meta, mime):\n    return value, mime\n\nMIME_RENDERERS = {\n    \"image/png\": render_image,\n    \"image/jpeg\": render_image,\n    \"image/svg+xml\": identity,\n    \"application/json\": identity,\n    \"application/javascript\": render_javascript,\n    \"application/pdf\": render_pdf,\n    \"text/html\": identity,\n    \"text/markdown\": render_markdown,\n    \"text/plain\": identity,\n}\n\ndef eval_formatter(obj, print_method):\n    \"\"\"\n    Evaluates a formatter method.\n    \"\"\"\n    if print_method == \"__repr__\":\n        return repr(obj)\n    elif hasattr(obj, print_method):\n        if print_method == \"savefig\":\n            buf = io.BytesIO()\n            obj.savefig(buf, format=\"png\")\n            buf.seek(0)\n            return base64.b64encode(buf.read()).decode(\"utf-8\")\n        return getattr(obj, print_method)()\n    elif print_method == \"_repr_mimebundle_\":\n        return {}, {}\n    return None\n\ndef format_mime(obj):\n    \"\"\"\n    Formats object using _repr_x_ methods.\n    \"\"\"\n    if isinstance(obj, str):\n        return escape(obj), \"text/plain\"\n    mimebundle = eval_formatter(obj, \"_repr_mimebundle_\")\n    if isinstance(mimebundle, tuple):\n        format_dict, _ = mimebundle\n    else:\n        format_dict = mimebundle\n\n    output, not_available = None, []\n    for method, mime_type in reversed(list(MIME_METHODS.items())):\n        if mime_type in format_dict:\n            output = format_dict[mime_type]\n        elif isinstance(obj, type) and method != '__repr__':\n            output = None\n        else:\n            output = eval_formatter(obj, method)\n\n        if output is None:\n            continue\n        elif mime_type not in MIME_RENDERERS:\n            not_available.append(mime_type)\n            continue\n        break\n    if output is None:\n        output = repr(output)\n        mime_type = \"text/plain\"\n    elif isinstance(output, tuple):\n        output, meta = output\n    else:\n        meta = {}\n    content, mime_type = MIME_RENDERERS[mime_type](output, meta, mime_type)\n    if mime_type == 'text/plain':\n        content = escape(content)\n    return content, mime_type\n", "path": "panel/io/mime_render.py"}], "after_files": [{"content": "\"\"\"\nUtilities for executing Python code and rendering the resulting output\nusing a similar MIME-type based rendering system as implemented by\nIPython.\n\nAttempts to limit the actual MIME types that have to be rendered on\nto a minimum simplifying frontend implementation:\n\n    - application/bokeh: Model JSON representation\n    - text/plain: HTML escaped string output\n    - text/html: HTML code to insert into the DOM\n\"\"\"\n\nfrom __future__ import annotations\n\nimport ast\nimport base64\nimport copy\nimport io\nimport pathlib\nimport pkgutil\nimport sys\nimport traceback\n\nfrom contextlib import redirect_stderr, redirect_stdout\nfrom html import escape\nfrom textwrap import dedent\nfrom typing import Any, Dict, List\n\nimport markdown\n\n#---------------------------------------------------------------------\n# Import API\n#---------------------------------------------------------------------\n\ndef _stdlibs():\n    if sys.version_info[:2] >= (3, 10):\n        return sys.stdlib_module_names\n    env_dir = str(pathlib.Path(sys.executable).parent.parent)\n    modules = list(sys.builtin_module_names)\n    for m in pkgutil.iter_modules():\n        mpath = getattr(m.module_finder, 'path', '')\n        if mpath.startswith(env_dir) and 'site-packages' not in mpath:\n            modules.append(m.name)\n    return modules\n\n_STDLIBS = _stdlibs()\n_PACKAGE_MAP = {\n    'sklearn': 'scikit-learn',\n    'transformers_js': 'transformers-js-py',\n}\n_IGNORED_PKGS = ['js', 'pyodide']\n_PANDAS_AUTODETECT = ['bokeh.sampledata', 'as_frame']\n\ndef find_requirements(code: str) -> List[str]:\n    \"\"\"\n    Finds the packages required in a string of code.\n\n    Parameters\n    ----------\n    code : str\n       the Python code to run.\n\n    Returns\n    -------\n    ``List[str]``\n        A list of package names that are to be installed for the code to be able to run.\n\n    Examples\n    --------\n    >>> code = \"import numpy as np; import scipy.stats\"\n    >>> find_imports(code)\n    ['numpy', 'scipy']\n    \"\"\"\n    # handle mis-indented input from multi-line strings\n    code = dedent(code)\n\n    mod = ast.parse(code)\n    imports = set()\n    for node in ast.walk(mod):\n        if isinstance(node, ast.Import):\n            for name in node.names:\n                node_name = name.name\n                imports.add(node_name.split(\".\")[0])\n        elif isinstance(node, ast.ImportFrom):\n            module_name = node.module\n            if module_name is None:\n                continue\n            imports.add(module_name.split(\".\")[0])\n\n    packages = []\n    for pkg in sorted(imports):\n        pkg = _PACKAGE_MAP.get(pkg, pkg)\n        if pkg in _STDLIBS:\n            continue\n        elif isinstance(pkg, list):\n            packages.extend(pkg)\n        else:\n            packages.append(pkg)\n    if any(pdd in code for pdd in _PANDAS_AUTODETECT) and 'pandas' not in packages:\n        packages.append('pandas')\n    return [pkg for pkg in packages if pkg not in _IGNORED_PKGS]\n\n#---------------------------------------------------------------------\n# Execution API\n#---------------------------------------------------------------------\n\nclass WriteCallbackStream(io.StringIO):\n\n    def __init__(self, on_write=None, escape=True):\n        self._onwrite = on_write\n        self._escape = escape\n        super().__init__()\n\n    def write(self, s):\n        if self._onwrite:\n            self._onwrite(escape(s) if self._escape else s)\n        super().write(s)\n\ndef _convert_expr(expr: ast.Expr) -> ast.Expression:\n    \"\"\"\n    Converts an ast.Expr to and ast.Expression that can be compiled\n    and evaled.\n    \"\"\"\n    expr.lineno = 0\n    expr.col_offset = 0\n    return ast.Expression(expr.value, lineno=0, col_offset = 0)\n\n_OUT_BUFFER = []\n\ndef _display(*objs, **kwargs):\n    \"\"\"\n    IPython.display compatibility wrapper.\n\n    Note: This only handles a single display.\n    \"\"\"\n    _OUT_BUFFER.extend(list(objs))\n\ndef exec_with_return(\n    code: str,\n    global_context: Dict[str, Any] = None,\n    stdout: Any = None,\n    stderr: Any = None\n) -> Any:\n    \"\"\"\n    Executes a code snippet and returns the resulting output of the\n    last line.\n\n    Arguments\n    ---------\n    code: str\n        The code to execute\n    global_context: Dict[str, Any]\n        The globals to inject into the execution context.\n    stdout: io.StringIO\n        The stream to redirect stdout to.\n    stderr: io.StringIO\n        The stream to redirect stderr to.\n\n    Returns\n    -------\n\n    The return value of the executed code.\n    \"\"\"\n    global_context = global_context if global_context else globals()\n    global_context['display'] = _display\n    code_ast = ast.parse(code)\n\n    init_ast = copy.deepcopy(code_ast)\n    init_ast.body = code_ast.body[:-1]\n\n    last_ast = copy.deepcopy(code_ast)\n    last_ast.body = code_ast.body[-1:]\n\n    stdout = stdout or sys.stdout\n    stderr = stderr or sys.stderr\n    with redirect_stdout(stdout), redirect_stderr(stderr):\n        try:\n            exec(compile(init_ast, \"<ast>\", \"exec\"), global_context)\n            if not last_ast.body:\n                out = None\n            elif type(last_ast.body[0]) == ast.Expr:\n                out = eval(compile(_convert_expr(last_ast.body[0]), \"<ast>\", \"eval\"), global_context)\n            else:\n                exec(compile(last_ast, \"<ast>\", \"exec\"), global_context)\n                out = None\n            if code.strip().endswith(';'):\n                out = None\n            if _OUT_BUFFER and out is None:\n                out = _OUT_BUFFER[-1]\n        except Exception:\n            out = None\n            traceback.print_exc(file=stderr)\n        finally:\n            _OUT_BUFFER.clear()\n    return out\n\n#---------------------------------------------------------------------\n# MIME Render API\n#---------------------------------------------------------------------\n\nMIME_METHODS = {\n    \"__repr__\": \"text/plain\",\n    \"_repr_html_\": \"text/html\",\n    \"_repr_markdown_\": \"text/markdown\",\n    \"_repr_svg_\": \"image/svg+xml\",\n    \"_repr_png_\": \"image/png\",\n    \"_repr_pdf_\": \"application/pdf\",\n    \"_repr_jpeg_\": \"image/jpeg\",\n    \"_repr_latex\": \"text/latex\",\n    \"_repr_json_\": \"application/json\",\n    \"_repr_javascript_\": \"application/javascript\",\n    \"savefig\": \"image/png\",\n    \"to_html\": \"text/html\"\n}\n\n# Rendering function\n\ndef render_svg(value, meta, mime):\n    return value, 'text/html'\n\ndef render_image(value, meta, mime):\n    data = f\"data:{mime};charset=utf-8;base64,{value}\"\n    attrs = \" \".join(['{k}=\"{v}\"' for k, v in meta.items()])\n    return f'<img src=\"{data}\" {attrs}</img>', 'text/html'\n\ndef render_javascript(value, meta, mime):\n    return f'<script>{value}</script>', 'text/html'\n\ndef render_markdown(value, meta, mime):\n    return (markdown.markdown(\n        value, extensions=[\"extra\", \"smarty\", \"codehilite\"], output_format='html5'\n    ), 'text/html')\n\ndef render_pdf(value, meta, mime):\n    data = value.encode('utf-8')\n    base64_pdf = base64.b64encode(data).decode(\"utf-8\")\n    src = f\"data:application/pdf;base64,{base64_pdf}\"\n    return f'<embed src=\"{src}\" width=\"100%\" height=\"100%\" type=\"application/pdf\">', 'text/html'\n\ndef identity(value, meta, mime):\n    return value, mime\n\nMIME_RENDERERS = {\n    \"image/png\": render_image,\n    \"image/jpeg\": render_image,\n    \"image/svg+xml\": identity,\n    \"application/json\": identity,\n    \"application/javascript\": render_javascript,\n    \"application/pdf\": render_pdf,\n    \"text/html\": identity,\n    \"text/markdown\": render_markdown,\n    \"text/plain\": identity,\n}\n\ndef eval_formatter(obj, print_method):\n    \"\"\"\n    Evaluates a formatter method.\n    \"\"\"\n    if print_method == \"__repr__\":\n        return repr(obj)\n    elif hasattr(obj, print_method):\n        if print_method == \"savefig\":\n            buf = io.BytesIO()\n            obj.savefig(buf, format=\"png\")\n            buf.seek(0)\n            return base64.b64encode(buf.read()).decode(\"utf-8\")\n        return getattr(obj, print_method)()\n    elif print_method == \"_repr_mimebundle_\":\n        return {}, {}\n    return None\n\ndef format_mime(obj):\n    \"\"\"\n    Formats object using _repr_x_ methods.\n    \"\"\"\n    if isinstance(obj, str):\n        return escape(obj), \"text/plain\"\n    mimebundle = eval_formatter(obj, \"_repr_mimebundle_\")\n    if isinstance(mimebundle, tuple):\n        format_dict, _ = mimebundle\n    else:\n        format_dict = mimebundle\n\n    output, not_available = None, []\n    for method, mime_type in reversed(list(MIME_METHODS.items())):\n        if mime_type in format_dict:\n            output = format_dict[mime_type]\n        elif isinstance(obj, type) and method != '__repr__':\n            output = None\n        else:\n            output = eval_formatter(obj, method)\n\n        if output is None:\n            continue\n        elif mime_type not in MIME_RENDERERS:\n            not_available.append(mime_type)\n            continue\n        break\n    if output is None:\n        output = repr(output)\n        mime_type = \"text/plain\"\n    elif isinstance(output, tuple):\n        output, meta = output\n    else:\n        meta = {}\n    content, mime_type = MIME_RENDERERS[mime_type](output, meta, mime_type)\n    if mime_type == 'text/plain':\n        content = escape(content)\n    return content, mime_type\n", "path": "panel/io/mime_render.py"}]}