|
| 1 | +from typing import Dict, List, Union |
| 2 | +from uuid import uuid4 |
| 3 | + |
| 4 | +import y_py as Y |
| 5 | +from ypy_websocket.websocket_server import YDoc |
| 6 | + |
| 7 | + |
| 8 | +class YBaseDoc: |
| 9 | + def __init__(self, ydoc: YDoc): |
| 10 | + self._ydoc = ydoc |
| 11 | + self._ystate = self._ydoc.get_map("state") |
| 12 | + self._subscriptions = {} |
| 13 | + |
| 14 | + @property |
| 15 | + def ystate(self): |
| 16 | + return self._ystate |
| 17 | + |
| 18 | + @property |
| 19 | + def ydoc(self): |
| 20 | + return self._ydoc |
| 21 | + |
| 22 | + @property |
| 23 | + def source(self): |
| 24 | + raise RuntimeError("Y document source generation not implemented") |
| 25 | + |
| 26 | + @source.setter |
| 27 | + def source(self, value): |
| 28 | + raise RuntimeError("Y document source initialization not implemented") |
| 29 | + |
| 30 | + @property |
| 31 | + def dirty(self) -> None: |
| 32 | + return self._ystate["dirty"] |
| 33 | + |
| 34 | + @dirty.setter |
| 35 | + def dirty(self, value: bool) -> None: |
| 36 | + if self.dirty != value: |
| 37 | + with self._ydoc.begin_transaction() as t: |
| 38 | + self._ystate.set(t, "dirty", value) |
| 39 | + |
| 40 | + def observe(self, callback): |
| 41 | + raise RuntimeError("Y document observe not implemented") |
| 42 | + |
| 43 | + def unobserve(self): |
| 44 | + for k, v in self._subscriptions.items(): |
| 45 | + k.unobserve(v) |
| 46 | + self._subscriptions = {} |
| 47 | + |
| 48 | + |
| 49 | +class YFile(YBaseDoc): |
| 50 | + def __init__(self, *args, **kwargs): |
| 51 | + super().__init__(*args, **kwargs) |
| 52 | + self._ysource = self._ydoc.get_text("source") |
| 53 | + |
| 54 | + @property |
| 55 | + def source(self): |
| 56 | + return str(self._ysource) |
| 57 | + |
| 58 | + @source.setter |
| 59 | + def source(self, value): |
| 60 | + with self._ydoc.begin_transaction() as t: |
| 61 | + # clear document |
| 62 | + source_len = len(self._ysource) |
| 63 | + if source_len: |
| 64 | + self._ysource.delete(t, 0, source_len) |
| 65 | + # initialize document |
| 66 | + if value: |
| 67 | + self._ysource.push(t, value) |
| 68 | + |
| 69 | + def observe(self, callback): |
| 70 | + self._subscriptions[self._ysource] = self._ysource.observe(callback) |
| 71 | + |
| 72 | + |
| 73 | +class YNotebook(YBaseDoc): |
| 74 | + def __init__(self, *args, **kwargs): |
| 75 | + super().__init__(*args, **kwargs) |
| 76 | + self._ycells = self._ydoc.get_array("cells") |
| 77 | + self._ymeta = self._ydoc.get_map("meta") |
| 78 | + |
| 79 | + @property |
| 80 | + def source(self): |
| 81 | + cells = self._ycells.to_json() |
| 82 | + meta = self._ymeta.to_json() |
| 83 | + state = self._ystate.to_json() |
| 84 | + cast_all(cells, float, int) |
| 85 | + cast_all(meta, float, int) |
| 86 | + for cell in cells: |
| 87 | + if "id" in cell and state["nbformat"] == 4 and state["nbformatMinor"] <= 4: |
| 88 | + # strip cell IDs if we have notebook format 4.0-4.4 |
| 89 | + del cell["id"] |
| 90 | + return dict( |
| 91 | + cells=cells, |
| 92 | + metadata=meta["metadata"], |
| 93 | + nbformat=int(state["nbformat"]), |
| 94 | + nbformat_minor=int(state["nbformatMinor"]), |
| 95 | + ) |
| 96 | + |
| 97 | + @source.setter |
| 98 | + def source(self, value): |
| 99 | + cast_all(value, int, float) |
| 100 | + if not value["cells"]: |
| 101 | + value["cells"] = [ |
| 102 | + { |
| 103 | + "cell_type": "code", |
| 104 | + "execution_count": None, |
| 105 | + "metadata": {}, |
| 106 | + "outputs": [], |
| 107 | + "source": "", |
| 108 | + "id": str(uuid4()), |
| 109 | + } |
| 110 | + ] |
| 111 | + # workaround until ypy is fixed: https://github.com/davidbrochart/ypy-websocket/pull/9 |
| 112 | + ytexts_to_clear = [] |
| 113 | + with self._ydoc.begin_transaction() as t: |
| 114 | + # clear document |
| 115 | + cells_len = len(self._ycells) |
| 116 | + if cells_len: |
| 117 | + self._ycells.delete(t, 0, cells_len) |
| 118 | + for key in self._ymeta: |
| 119 | + self._ymeta.delete(t, key) |
| 120 | + for key in [k for k in self._ystate if k != "dirty"]: |
| 121 | + self._ystate.delete(t, key) |
| 122 | + |
| 123 | + # initialize document |
| 124 | + ycells = [] |
| 125 | + for cell in value["cells"]: |
| 126 | + cell_source = cell["source"] |
| 127 | + if cell_source: |
| 128 | + ytext = Y.YText(cell_source) |
| 129 | + else: |
| 130 | + ytext = Y.YText(" ") |
| 131 | + ytexts_to_clear.append(ytext) |
| 132 | + cell["source"] = ytext |
| 133 | + if "outputs" in cell: |
| 134 | + cell["outputs"] = Y.YArray(cell["outputs"]) |
| 135 | + ycell = Y.YMap(cell) |
| 136 | + ycells.append(ycell) |
| 137 | + |
| 138 | + if ycells: |
| 139 | + self._ycells.push(t, ycells) |
| 140 | + self._ymeta.set(t, "metadata", value["metadata"]) |
| 141 | + self._ystate.set(t, "nbformat", value["nbformat"]) |
| 142 | + self._ystate.set(t, "nbformatMinor", value["nbformat_minor"]) |
| 143 | + with self._ydoc.begin_transaction() as t: |
| 144 | + for ytext in ytexts_to_clear: |
| 145 | + ytext.delete(t, 0, 1) |
| 146 | + |
| 147 | + def observe(self, callback): |
| 148 | + self.unobserve() |
| 149 | + for cell in self._ycells: |
| 150 | + self._subscriptions[cell["source"]] = cell["source"].observe(callback) |
| 151 | + if "outputs" in cell: |
| 152 | + self._subscriptions[cell["outputs"]] = cell["outputs"].observe(callback) |
| 153 | + self._subscriptions[cell] = cell.observe(callback) |
| 154 | + self._subscriptions[self._ycells] = self._ycells.observe(callback) |
| 155 | + self._subscriptions[self._ymeta] = self._ymeta.observe(callback) |
| 156 | + |
| 157 | + |
| 158 | +def cast_all(o: Union[List, Dict], from_type, to_type) -> None: |
| 159 | + if isinstance(o, list): |
| 160 | + for i, v in enumerate(o): |
| 161 | + if isinstance(v, from_type): |
| 162 | + o[i] = to_type(v) |
| 163 | + elif isinstance(v, (list, dict)): |
| 164 | + cast_all(v, from_type, to_type) |
| 165 | + elif isinstance(o, dict): |
| 166 | + for k, v in o.items(): |
| 167 | + if isinstance(v, from_type): |
| 168 | + o[k] = to_type(v) |
| 169 | + elif isinstance(v, (list, dict)): |
| 170 | + cast_all(v, from_type, to_type) |
0 commit comments