|
| 1 | +import json |
| 2 | +import os |
| 3 | +from pathlib import Path, PurePath |
| 4 | +import shutil |
| 5 | + |
| 6 | +from pycrdt import Map |
| 7 | + |
| 8 | +from traitlets.config import LoggingConfigurable |
| 9 | +from traitlets import ( |
| 10 | + Any, |
| 11 | + Bool, |
| 12 | + Dict, |
| 13 | + Instance, |
| 14 | + List, |
| 15 | + TraitError, |
| 16 | + Type, |
| 17 | + Unicode, |
| 18 | + Int, |
| 19 | + default, |
| 20 | + validate, |
| 21 | +) |
| 22 | + |
| 23 | +from jupyter_core.paths import jupyter_runtime_dir |
| 24 | + |
| 25 | +class OutputsManager(LoggingConfigurable): |
| 26 | + |
| 27 | + _last_output_index = Dict(default_value={}) |
| 28 | + _stream_count = Dict(default_value={}) |
| 29 | + |
| 30 | + outputs_path = Instance(PurePath, help="The local runtime dir") |
| 31 | + stream_limit = Int(default_value=10, config=True, allow_none=True) |
| 32 | + |
| 33 | + @default("outputs_path") |
| 34 | + def _default_outputs_path(self): |
| 35 | + return Path(jupyter_runtime_dir()) / "outputs" |
| 36 | + |
| 37 | + def _ensure_path(self, file_id, cell_id): |
| 38 | + nested_dir = self.outputs_path / file_id / cell_id |
| 39 | + self.log.info(f"Creating directory: {nested_dir}") |
| 40 | + nested_dir.mkdir(parents=True, exist_ok=True) |
| 41 | + |
| 42 | + def _build_path(self, file_id, cell_id=None, output_index=None): |
| 43 | + path = self.outputs_path / file_id |
| 44 | + if cell_id is not None: |
| 45 | + path = path / cell_id |
| 46 | + if output_index is not None: |
| 47 | + path = path / f"{output_index}.output" |
| 48 | + return path |
| 49 | + |
| 50 | + def get_output(self, file_id, cell_id, output_index): |
| 51 | + """Get an outputs by file_id, cell_id, and output_index.""" |
| 52 | + self.log.info(f"OutputsManager.get: {file_id} {cell_id} {output_index}") |
| 53 | + path = self._build_path(file_id, cell_id, output_index) |
| 54 | + if not os.path.isfile(path): |
| 55 | + raise FileNotFoundError(f"The output file doesn't exist: {path}") |
| 56 | + with open(path, "r", encoding="utf-8") as f: |
| 57 | + output = json.loads(f.read()) |
| 58 | + return output |
| 59 | + |
| 60 | + def get_stream(self, file_id, cell_id): |
| 61 | + "Get the stream output for a cell by file_id and cell_id." |
| 62 | + path = self._build_path(file_id, cell_id) / "stream" |
| 63 | + if not os.path.isfile(path): |
| 64 | + raise FileNotFoundError(f"The output file doesn't exist: {path}") |
| 65 | + with open(path, "r", encoding="utf-8") as f: |
| 66 | + output = f.read() |
| 67 | + return output |
| 68 | + |
| 69 | + def write(self, file_id, cell_id, output): |
| 70 | + """Write a new output for file_id and cell_id.""" |
| 71 | + self.log.info(f"OutputsManager.write: {file_id} {cell_id} {output}") |
| 72 | + result = self.write_output(file_id, cell_id, output) |
| 73 | + if output["output_type"] == "stream" and self.stream_limit is not None: |
| 74 | + result = self.write_stream(file_id, cell_id, output) |
| 75 | + return result |
| 76 | + |
| 77 | + def write_output(self, file_id, cell_id, output): |
| 78 | + self._ensure_path(file_id, cell_id) |
| 79 | + last_index = self._last_output_index.get(cell_id, -1) |
| 80 | + index = last_index + 1 |
| 81 | + self._last_output_index[cell_id] = index |
| 82 | + path = self._build_path(file_id, cell_id, index) |
| 83 | + data = json.dumps(output, ensure_ascii=False) |
| 84 | + with open(path, "w", encoding="utf-8") as f: |
| 85 | + f.write(data) |
| 86 | + url = f"/api/outputs/{file_id}/{cell_id}/{index}.output" |
| 87 | + return Map({}) |
| 88 | + |
| 89 | + def write_stream(self, file_id, cell_id, output) -> Map: |
| 90 | + # How many stream outputs have been written for this cell previously |
| 91 | + count = self._stream_count.get(cell_id, 0) |
| 92 | + |
| 93 | + # Go ahead and write the incoming stream |
| 94 | + self._ensure_path(file_id, cell_id) |
| 95 | + path = self._build_path(file_id, cell_id) / "stream" |
| 96 | + text = output["text"] |
| 97 | + mode = 'a' if os.path.isfile(path) else 'w' |
| 98 | + with open(path, "a", encoding="utf-8") as f: |
| 99 | + f.write(text) |
| 100 | + url = f"/api/outputs/{file_id}/{cell_id}/stream" |
| 101 | + |
| 102 | + # Increment the count |
| 103 | + count = count + 1 |
| 104 | + self._stream_count[cell_id] = count |
| 105 | + |
| 106 | + # Now create the placeholder output |
| 107 | + if count < self.stream_limit: |
| 108 | + # Return the original if we haven't reached the limit |
| 109 | + placeholder = Map(output) |
| 110 | + elif count == self.stream_limit: |
| 111 | + # Return a link to the full stream output |
| 112 | + placeholder = Map({ |
| 113 | + "output_type": "display_data", |
| 114 | + "data": { |
| 115 | + 'text/html': f'<a href="{url}">Click this link to see the full stream output</a>' |
| 116 | + } |
| 117 | + }) |
| 118 | + elif count > self.stream_limit: |
| 119 | + placeholder = None |
| 120 | + return placeholder |
| 121 | + |
| 122 | + def clear(self, file_id, cell_id=None): |
| 123 | + """Clear the state of the manager.""" |
| 124 | + if cell_id is None: |
| 125 | + self._stream_count = {} |
| 126 | + path = self._build_path(file_id) |
| 127 | + else: |
| 128 | + try: |
| 129 | + del self._stream_count[cell_id] |
| 130 | + except KeyError: |
| 131 | + pass |
| 132 | + path = self._build_path(file_id, cell_id) |
| 133 | + shutil.rmtree(path) |
0 commit comments