Debian Codegraph @

pyinstrument/renderers/html.py

raw symbols SCIP
1 from __future__ import annotations
2
3 import codecs
4 import json
5 import sys
6 import tempfile
7 import urllib.parse
8 import warnings
9 import webbrowser
10 from pathlib import Path
11 from typing import Any
12
13 from pyinstrument.renderers.base import FrameRenderer, ProcessorList, Renderer
14 from pyinstrument.session import Session
15
16 # pyright: strict
17
18
19 class HTMLRenderer(Renderer):
20 """
21 Renders a rich, interactive web page, as a string of HTML.
22 """
23
24 output_file_extension = "html"
25
26 preprocessors: ProcessorList
27 """
28 Preprocessors installed on this renderer. This property is similar to
29 :attr:`FrameRenderer.processors`, but all pyinstrument's processing is
30 done in the webapp, so these are only used to modify the JSON data sent to
31 the webapp. For example, you might want to use preprocessors to remove
32 unneeded frames from the data to reduce the size of the HTML file.
33 """
34
35 preprocessor_options: dict[str, Any]
36 """
37 Options to pass to the preprocessors, like :attr:`FrameRenderer.processor_options`.
38 """
39
40 def __init__(
41 self,
42 *,
43 resample_interval: float | None = None,
44 show_all: bool = False,
45 timeline: bool = False,
46 ):
47 """
48 :param resample_interval: Controls how the renderer deals with very large sessions. The typically struggles with sessions of more than 100,000 samples. If the session has more samples than this number, it will be automatically resampled to a coarser interval. You can control this interval with this parameter. If None (the default), the interval will be chosen automatically. Setting this to 0 disables resampling.
49 """
50 super().__init__()
51 if show_all:
52 warnings.warn(
53 f"the show_all option is deprecated on the HTML renderer, and has no effect. Use the view options in the webpage instead.",
54 DeprecationWarning,
55 stacklevel=3,
56 )
57 if timeline:
58 warnings.warn(
59 f"timeline is deprecated on the HTML renderer, and has no effect. Use the timeline view in the webpage instead.",
60 DeprecationWarning,
61 stacklevel=3,
62 )
63
64 self.resample_interval = resample_interval
65
66 # These settings are passed down to JSONForHTMLRenderer, and can be
67 # used to modify its output. E.g. they can be used to lower the size
68 # of the output file, by excluding function calls which take a small
69 # fraction of total time.
70 self.preprocessors = []
71 self.preprocessor_options = {}
72
73 def render(self, session: Session):
74 if len(session.frame_records) > 100_000:
75 original_session = session
76 resample_interval = self.resample_interval
77 if resample_interval is None:
78 # auto mode: choose an interval that gives us 0.01% resolution
79 resample_interval = session.duration / 10000
80
81 if resample_interval > 0:
82 session = original_session.resample(interval=resample_interval)
83
84 while len(session.frame_records) > 100_000:
85 resample_interval *= 2
86 session = original_session.resample(interval=resample_interval)
87 print(
88 f"pyinstrument: session has {len(original_session.frame_records)} samples, which is too many for the HTML renderer to handle. Resampled to {len(session.frame_records)} samples with interval {resample_interval:.6f} seconds. Set the renderer option resample_interval to control this behaviour.",
89 file=sys.stderr,
90 )
91
92 json_renderer = JSONForHTMLRenderer()
93 json_renderer.processors = self.preprocessors
94 json_renderer.processor_options = self.preprocessor_options
95 session_json = json_renderer.render(session)
96
97 resources_dir = Path(__file__).parent / "html_resources"
98
99 js_file = resources_dir / "app.js"
100 css_file = resources_dir / "app.css"
101
102 if not js_file.exists() or not css_file.exists():
103 raise RuntimeError(
104 "Could not find app.js / app.css. Perhaps you need to run bin/build_js_bundle.py?"
105 )
106
107 js = js_file.read_text(encoding="utf-8")
108 css = css_file.read_text(encoding="utf-8")
109
110 page = f"""<!DOCTYPE html>
111 <html>
112 <head>
113 <meta charset="utf-8">
114 </head>
115 <body>
116 <div id="app"></div>
117
118 <script>{js}</script>
119 <style>{css}</style>
120
121 <script>
122 const sessionData = {session_json};
123 pyinstrumentHTMLRenderer.render(document.getElementById('app'), sessionData);
124 </script>
125 </body>
126 </html>
127 """
128
129 return page
130
131 def open_in_browser(self, session: Session, output_filename: str | None = None):
132 """
133 Open the rendered HTML in a webbrowser.
134
135 If output_filename=None (the default), a tempfile is used.
136
137 The filename of the HTML file is returned.
138
139 """
140 if output_filename is None:
141 output_file = tempfile.NamedTemporaryFile(suffix=".html", delete=False)
142 output_filename = output_file.name
143 with codecs.getwriter("utf-8")(output_file) as f:
144 f.write(self.render(session))
145 else:
146 with codecs.open(output_filename, "w", "utf-8") as f:
147 f.write(self.render(session))
148
149 url = urllib.parse.urlunparse(("file", "", output_filename, "", "", ""))
150 webbrowser.open(url)
151 return output_filename
152
153
154 class JSONForHTMLRenderer(FrameRenderer):
155 """
156 The HTML takes a special form of JSON-encoded session, which includes
157 an unprocessed frame tree rather than a list of frame records. This
158 reduces the amount of parsing code that must be included in the
159 Typescript renderer.
160 """
161
162 output_file_extension = "json"
163
164 def default_processors(self) -> ProcessorList:
165 return []
166
167 def render(self, session: Session) -> str:
168 session_json = session.to_json(include_frame_records=False)
169 session_json_str = json.dumps(session_json)
170 root_frame = session.root_frame()
171 root_frame = self.preprocess(root_frame)
172 frame_tree_json_str = root_frame.to_json_str() if root_frame else "null"
173 return '{"session": %s, "frame_tree": %s}' % (session_json_str, frame_tree_json_str)