thzdaq-gui 0.0.6b4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. thzdaq_gui/__init__.py +1 -0
  2. thzdaq_gui/__main__.py +5 -0
  3. thzdaq_gui/app.py +166 -0
  4. thzdaq_gui/approval_dialog.py +243 -0
  5. thzdaq_gui/ask_box.py +78 -0
  6. thzdaq_gui/assistant/__init__.py +4 -0
  7. thzdaq_gui/assistant/attachments.py +106 -0
  8. thzdaq_gui/assistant/conversation.py +278 -0
  9. thzdaq_gui/assistant/hints.py +155 -0
  10. thzdaq_gui/assistant/keys.py +51 -0
  11. thzdaq_gui/assistant/prompt.py +57 -0
  12. thzdaq_gui/assistant/provider.py +419 -0
  13. thzdaq_gui/bridge.py +78 -0
  14. thzdaq_gui/chat_widgets.py +273 -0
  15. thzdaq_gui/code_docks.py +238 -0
  16. thzdaq_gui/collapsible.py +103 -0
  17. thzdaq_gui/console_docks.py +139 -0
  18. thzdaq_gui/console_output.py +203 -0
  19. thzdaq_gui/device_docks.py +107 -0
  20. thzdaq_gui/device_types.py +20 -0
  21. thzdaq_gui/dock_names.py +72 -0
  22. thzdaq_gui/docking.py +495 -0
  23. thzdaq_gui/docks/__init__.py +0 -0
  24. thzdaq_gui/docks/assistant.py +526 -0
  25. thzdaq_gui/docks/body.py +87 -0
  26. thzdaq_gui/docks/code.py +449 -0
  27. thzdaq_gui/docks/console.py +316 -0
  28. thzdaq_gui/docks/custom.py +220 -0
  29. thzdaq_gui/docks/daemon.py +332 -0
  30. thzdaq_gui/docks/data.py +212 -0
  31. thzdaq_gui/docks/devices.py +1066 -0
  32. thzdaq_gui/docks/log.py +159 -0
  33. thzdaq_gui/docks/measure.py +822 -0
  34. thzdaq_gui/docks/processes.py +169 -0
  35. thzdaq_gui/docks/providers.py +230 -0
  36. thzdaq_gui/docks/raw.py +107 -0
  37. thzdaq_gui/docks/safety.py +331 -0
  38. thzdaq_gui/docks/setup.py +788 -0
  39. thzdaq_gui/docks/tabbed.py +149 -0
  40. thzdaq_gui/editor.py +738 -0
  41. thzdaq_gui/exit_dialog.py +127 -0
  42. thzdaq_gui/external_editor.py +87 -0
  43. thzdaq_gui/fields.py +170 -0
  44. thzdaq_gui/folders.py +65 -0
  45. thzdaq_gui/forms.py +523 -0
  46. thzdaq_gui/graph_docks.py +218 -0
  47. thzdaq_gui/graphs.py +944 -0
  48. thzdaq_gui/guide.py +118 -0
  49. thzdaq_gui/iv_analysis.py +276 -0
  50. thzdaq_gui/json_view.py +299 -0
  51. thzdaq_gui/kernel.py +339 -0
  52. thzdaq_gui/main_window.py +573 -0
  53. thzdaq_gui/measure_forms.py +89 -0
  54. thzdaq_gui/measurements.py +253 -0
  55. thzdaq_gui/models/__init__.py +2 -0
  56. thzdaq_gui/models/approvals.py +69 -0
  57. thzdaq_gui/models/assistant.py +547 -0
  58. thzdaq_gui/models/code.py +252 -0
  59. thzdaq_gui/models/console.py +277 -0
  60. thzdaq_gui/models/daemon.py +179 -0
  61. thzdaq_gui/models/device.py +181 -0
  62. thzdaq_gui/models/hints.py +139 -0
  63. thzdaq_gui/models/interpreter.py +77 -0
  64. thzdaq_gui/models/run.py +240 -0
  65. thzdaq_gui/models/runs.py +128 -0
  66. thzdaq_gui/models/scripts.py +266 -0
  67. thzdaq_gui/navigator.py +446 -0
  68. thzdaq_gui/overlay.py +138 -0
  69. thzdaq_gui/popup.py +129 -0
  70. thzdaq_gui/procedure_groups.py +40 -0
  71. thzdaq_gui/processes.py +109 -0
  72. thzdaq_gui/profile.py +73 -0
  73. thzdaq_gui/resources/arrows/down-disabled.svg +1 -0
  74. thzdaq_gui/resources/arrows/down-hover.svg +1 -0
  75. thzdaq_gui/resources/arrows/down-normal.svg +1 -0
  76. thzdaq_gui/resources/arrows/up-disabled.svg +1 -0
  77. thzdaq_gui/resources/arrows/up-hover.svg +1 -0
  78. thzdaq_gui/resources/arrows/up-normal.svg +1 -0
  79. thzdaq_gui/resources/docks.css +374 -0
  80. thzdaq_gui/resources/icon/thzdaq_128.png +0 -0
  81. thzdaq_gui/resources/icon/thzdaq_16.png +0 -0
  82. thzdaq_gui/resources/icon/thzdaq_256.png +0 -0
  83. thzdaq_gui/resources/icon/thzdaq_32.png +0 -0
  84. thzdaq_gui/resources/icon/thzdaq_48.png +0 -0
  85. thzdaq_gui/resources/icon/thzdaq_64.png +0 -0
  86. thzdaq_gui/review.py +155 -0
  87. thzdaq_gui/review_bar.py +105 -0
  88. thzdaq_gui/run_controls.py +230 -0
  89. thzdaq_gui/run_graphs.py +55 -0
  90. thzdaq_gui/runbar.py +335 -0
  91. thzdaq_gui/safe_state.py +75 -0
  92. thzdaq_gui/script_output.py +98 -0
  93. thzdaq_gui/session.py +324 -0
  94. thzdaq_gui/settings.py +136 -0
  95. thzdaq_gui/theme.py +314 -0
  96. thzdaq_gui/update_dialog.py +311 -0
  97. thzdaq_gui/updater.py +301 -0
  98. thzdaq_gui/updates.py +289 -0
  99. thzdaq_gui/version.py +4 -0
  100. thzdaq_gui/viewer.py +197 -0
  101. thzdaq_gui/wheel.py +47 -0
  102. thzdaq_gui/wording.py +7 -0
  103. thzdaq_gui/workers.py +106 -0
  104. thzdaq_gui/workspace.py +96 -0
  105. thzdaq_gui/workspace_menu.py +217 -0
  106. thzdaq_gui/workspace_settings.py +183 -0
  107. thzdaq_gui-0.0.6b4.dist-info/METADATA +47 -0
  108. thzdaq_gui-0.0.6b4.dist-info/RECORD +111 -0
  109. thzdaq_gui-0.0.6b4.dist-info/WHEEL +4 -0
  110. thzdaq_gui-0.0.6b4.dist-info/entry_points.txt +2 -0
  111. thzdaq_gui-0.0.6b4.dist-info/licenses/LICENSE +21 -0
thzdaq_gui/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """ThzDAQ desktop application: Qt views over thzdaq-core."""
thzdaq_gui/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from thzdaq_gui.app import main
4
+
5
+ sys.exit(main())
thzdaq_gui/app.py ADDED
@@ -0,0 +1,166 @@
1
+ """The desktop application: a client of the bench daemon. It connects to the
2
+ daemon of the instruments (or of their simulator) and starts it when none
3
+ runs; closing the window leaves the daemon to its measurements. With --plot
4
+ it is only the plots window of one measurement (viewer.py)."""
5
+
6
+ import argparse
7
+ import logging
8
+ import sys
9
+ from pathlib import Path
10
+ from typing import List, Optional
11
+
12
+ from PySide6.QtCore import Qt, QTimer
13
+ from PySide6.QtWidgets import QApplication, QMessageBox, QSplashScreen
14
+ from thzdaq_api import windows
15
+ from thzdaq_api.errors import LabError
16
+ from thzdaq_api.host import SIMULATE, connect_or_start
17
+ from thzdaq_api.origins import GUI
18
+ from thzdaq_api.workspace import NO_PROFILE, expected_profile, profile_path
19
+
20
+ from thzdaq_gui import theme, viewer
21
+ from thzdaq_gui.main_window import MainWindow
22
+ from thzdaq_gui.session import Session
23
+ from thzdaq_gui.settings import (
24
+ STATION_PATH,
25
+ app_dir,
26
+ settings,
27
+ stations_dir,
28
+ use_file,
29
+ )
30
+ from thzdaq_gui.wording import STATION_PROFILE
31
+ from thzdaq_gui.workspace import default_workspace
32
+
33
+ DAEMON = "ThzDAQ daemon"
34
+
35
+
36
+ def main(argv: Optional[List[str]] = None) -> int:
37
+ parser = argparse.ArgumentParser(
38
+ prog="thzdaq-gui", description="ThzDAQ desktop application"
39
+ )
40
+ parser.add_argument(
41
+ "--station", help="station profile (YAML) to work with; the daemon loads it"
42
+ )
43
+ parser.add_argument(
44
+ SIMULATE, action="store_true", help="work with the simulator's daemon"
45
+ )
46
+ parser.add_argument(
47
+ windows.WORKSPACE,
48
+ help="the folder whose data/ gets the measurements (default: the one "
49
+ "made the default, else the program's)",
50
+ )
51
+ parser.add_argument(
52
+ "--settings", help="keep settings in this INI file instead of the registry"
53
+ )
54
+ parser.add_argument(
55
+ windows.PLOT, type=windows.which, metavar=windows.WHICH,
56
+ help=f"only the plots of {windows.WHICH_HELP}",
57
+ ) # fmt: skip
58
+ windows.add_options(parser)
59
+ parser.add_argument(
60
+ "--quit-after", type=float, metavar="SECONDS", help=argparse.SUPPRESS
61
+ ) # smoke test of a build
62
+ args, qt_args = parser.parse_known_args(argv)
63
+
64
+ if sys.platform == "win32":
65
+ # Own taskbar button and icon, also when run from sources by python.exe
66
+ import ctypes
67
+
68
+ ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("ThzDAQ.ThzDAQ")
69
+ logging.basicConfig(
70
+ level=logging.INFO, format="%(asctime)s [%(name)s] %(levelname)s %(message)s"
71
+ )
72
+ app = QApplication.instance() or QApplication([sys.argv[0], *qt_args])
73
+ # Garbage collection only in the GUI thread, on a timer: a collection
74
+ # started in a device or measurement thread may free Qt objects there
75
+ from pyqtgraph.util.garbage_collector import GarbageCollector
76
+
77
+ collector = GarbageCollector(interval=1.0) # noqa: F841 (kept while running)
78
+ app.setApplicationName("ThzDAQ")
79
+ theme.apply(app)
80
+ app.setWindowIcon(theme.app_icon())
81
+ if args.plot is not None:
82
+ return show_plots(app, args)
83
+ if args.settings:
84
+ use_file(args.settings)
85
+ # Folders of an earlier update left in the system temp folder
86
+ from thzdaq_gui.updates import clean_leftovers
87
+
88
+ clean_leftovers()
89
+ folder = Path(args.workspace) if args.workspace else default_workspace()
90
+ station = start_profile(args.station, folder)
91
+ session = Session(
92
+ lambda simulate, origin=GUI, kind=GUI, window="": connect_or_start(
93
+ simulate, station, origin, kind, window=window
94
+ ),
95
+ folder,
96
+ )
97
+ # The lab comes first: its devices get docks the saved layout restores
98
+ splash = QSplashScreen(theme.app_icon().pixmap(128, 128))
99
+ splash.showMessage(
100
+ "Connecting to the ThzDAQ daemon…", Qt.AlignBottom | Qt.AlignHCenter
101
+ )
102
+ splash.show()
103
+ app.processEvents()
104
+ try:
105
+ session.open(args.simulate)
106
+ except LabError as e:
107
+ splash.close()
108
+ QMessageBox.critical(None, DAEMON, f"{e.message}\n\n{e.hint}".strip())
109
+ return 1
110
+ window = MainWindow(session, check_updates=args.quit_after is None)
111
+ window.show()
112
+ splash.finish(window)
113
+ if args.station:
114
+ offer_profile(window, session, args.station)
115
+ else:
116
+ window.workspaceMenu.check_profile()
117
+ if args.quit_after is not None:
118
+ window.confirm_exit = False
119
+ QTimer.singleShot(int(args.quit_after * 1000), window.close)
120
+ return app.exec()
121
+
122
+
123
+ def show_plots(app: QApplication, args: argparse.Namespace) -> int:
124
+ """Only the plots of one measurement, until the window is closed."""
125
+ try:
126
+ window = viewer.open_window(args.plot, args.simulate, windows.OwnPlot.of(args))
127
+ except LabError as e:
128
+ QMessageBox.critical(None, viewer.PROGRAM, f"{e.message}\n\n{e.hint}".strip())
129
+ return 1
130
+ window.show()
131
+ if args.quit_after is not None:
132
+ QTimer.singleShot(int(args.quit_after * 1000), window.close)
133
+ return app.exec()
134
+
135
+
136
+ def start_profile(given: Optional[str], folder: Path) -> Optional[str]:
137
+ """The profile a daemon this program starts loads: the one given, else the
138
+ one the workspace expects, else the last one worked with, else
139
+ stations/lab.yaml when it exists."""
140
+ try:
141
+ expected = expected_profile(folder)
142
+ except LabError: # a broken thzdaq.toml: the window tells it once open
143
+ expected = None
144
+ for candidate in (
145
+ given,
146
+ expected and profile_path(app_dir(), expected),
147
+ settings().value(STATION_PATH),
148
+ stations_dir() / "lab.yaml",
149
+ ):
150
+ if candidate and Path(candidate).exists():
151
+ return str(candidate)
152
+ return None
153
+
154
+
155
+ def offer_profile(window: MainWindow, session: Session, path: str) -> None:
156
+ """The daemon already worked with another profile: switch only when asked."""
157
+ loaded = session.profile().path
158
+ if loaded is not None and Path(loaded).resolve() == Path(path).resolve():
159
+ return
160
+ answer = QMessageBox.question(
161
+ window,
162
+ STATION_PROFILE,
163
+ f"The daemon works with {loaded or NO_PROFILE}. Switch it to {path}?",
164
+ )
165
+ if answer == QMessageBox.Yes:
166
+ window.load_profile(path)
@@ -0,0 +1,243 @@
1
+ """An agent asks a person: allow an operation (perhaps with another value) or
2
+ not, with words the agent reads; or answer its question. One modal dialog at a
3
+ time; one answered elsewhere closes.
4
+
5
+ What it asks may be long (a script it writes, as the lines it changes; a
6
+ raw command): then it shows in a box that scrolls both ways, in a fixed
7
+ font, a change coloured by line. The dialog never outgrows the screen, and
8
+ its answer and buttons stay in sight below."""
9
+
10
+ from collections import deque
11
+ from typing import Deque, Optional
12
+
13
+ from PySide6.QtCore import QObject, QSize, Qt
14
+ from PySide6.QtGui import QColor, QFontDatabase, QSyntaxHighlighter, QTextCharFormat
15
+ from PySide6.QtWidgets import (
16
+ QApplication,
17
+ QComboBox,
18
+ QDialog,
19
+ QDialogButtonBox,
20
+ QFormLayout,
21
+ QLabel,
22
+ QLineEdit,
23
+ QPlainTextEdit,
24
+ QVBoxLayout,
25
+ QWidget,
26
+ )
27
+ from thzdaq_api.approvals import Approval
28
+
29
+ from thzdaq_gui import theme
30
+ from thzdaq_gui.chat_widgets import ElidedLabel
31
+ from thzdaq_gui.models.approvals import ApprovalsModel
32
+
33
+ LINE = 240 # letters of a text shown as a line; longer: in a box
34
+ WORD = 60 # letters of a word a line may hold; longer: in a box
35
+ SCREEN = 0.85 # the share of the screen the dialog may take
36
+ WIDTH = 560 # the dialog's least width
37
+
38
+
39
+ def long(text: str) -> bool:
40
+ """Shown in a box that scrolls: lines, or more than a line holds."""
41
+ return "\n" in text or len(text) > LINE or any(len(w) > WORD for w in text.split())
42
+
43
+
44
+ class ChangeColors(QSyntaxHighlighter):
45
+ """A change as its lines: added, removed, and where (@@)."""
46
+
47
+ def highlightBlock(self, text: str) -> None:
48
+ color = (
49
+ theme.GOOD if text.startswith("+")
50
+ else theme.BAD if text.startswith("-")
51
+ else theme.MUTED if text.startswith("@@")
52
+ else None
53
+ ) # fmt: skip
54
+ if color is not None:
55
+ found = QTextCharFormat()
56
+ found.setForeground(QColor(color))
57
+ self.setFormat(0, len(text), found)
58
+
59
+
60
+ class TextBox(QPlainTextEdit):
61
+ """A long text to read: it scrolls both ways, as tall as its lines up to
62
+ what the screen leaves."""
63
+
64
+ def __init__(self, text: str, most: int, parent=None):
65
+ super().__init__(text, parent)
66
+ self.setReadOnly(True)
67
+ self.setLineWrapMode(QPlainTextEdit.NoWrap)
68
+ self.setFont(QFontDatabase.systemFont(QFontDatabase.FixedFont))
69
+ self.colors = ChangeColors(self.document())
70
+ lines = text.count("\n") + 1
71
+ self.wanted = QSize(
72
+ self.fontMetrics().horizontalAdvance("x") * min(120, longest(text)) + 32,
73
+ min(most, lines * self.fontMetrics().lineSpacing() + 16),
74
+ )
75
+
76
+ def sizeHint(self) -> QSize:
77
+ return self.wanted
78
+
79
+
80
+ def longest(text: str) -> int:
81
+ return max((len(line) for line in text.splitlines()), default=0)
82
+
83
+
84
+ class ApprovalDialog(QDialog):
85
+ def __init__(self, approval: Approval, model: ApprovalsModel, parent=None):
86
+ super().__init__(parent)
87
+ self.approval = approval
88
+ self.model = model
89
+ question = not approval.operation
90
+ self.setWindowTitle("Question" if question else "Allow?")
91
+ self.setWindowIcon(theme.icon("robot-outline"))
92
+ self.setWindowModality(Qt.ApplicationModal)
93
+ layout = QVBoxLayout(self)
94
+ who = QLabel(f"{approval.origin} {'asks' if question else 'wants to'}:")
95
+ who.setProperty("role", "muted")
96
+ title = ElidedLabel(approval.title, mode=Qt.ElideMiddle)
97
+ title.setProperty("role", "title")
98
+ screen = parent.screen() if parent else QApplication.primaryScreen()
99
+ room = screen.availableGeometry()
100
+ if long(approval.text):
101
+ self.text: QWidget = TextBox(approval.text, int(room.height() * 0.6))
102
+ else:
103
+ self.text = QLabel(approval.text)
104
+ self.text.setWordWrap(True)
105
+ self.text.setTextInteractionFlags(Qt.TextSelectableByMouse)
106
+ layout.addWidget(who)
107
+ layout.addWidget(title)
108
+ layout.addWidget(self.text, 1)
109
+ if approval.warning:
110
+ warning = QLabel(approval.warning)
111
+ warning.setWordWrap(True)
112
+ warning.setStyleSheet(f"color: {theme.ACCENT}")
113
+ layout.addWidget(warning)
114
+ form = QFormLayout()
115
+ self.value: Optional[QLineEdit] = None
116
+ if approval.value is not None: # the person may set another value
117
+ self.value = QLineEdit(approval.value)
118
+ form.addRow("Value", self.value)
119
+ self.choice: Optional[QComboBox] = None
120
+ if approval.options:
121
+ self.choice = QComboBox()
122
+ self.choice.addItems(approval.options)
123
+ form.addRow("Answer", self.choice)
124
+ self.confirm: Optional[QLineEdit] = None
125
+ if approval.confirm:
126
+ self.confirm = QLineEdit()
127
+ self.confirm.setPlaceholderText(approval.confirm)
128
+ form.addRow(f"Type {approval.confirm}", self.confirm)
129
+ self.words = QLineEdit()
130
+ self.words.setPlaceholderText(
131
+ "your answer" if question else "for the agent: why not, what instead"
132
+ )
133
+ form.addRow("Words", self.words)
134
+ layout.addLayout(form)
135
+ self.status = QLabel()
136
+ self.status.setStyleSheet(f"color: {theme.ACCENT}")
137
+ self.status.hide()
138
+ layout.addWidget(self.status)
139
+ buttons = QDialogButtonBox()
140
+ self.allow = buttons.addButton(
141
+ "Answer" if question else "Allow", QDialogButtonBox.AcceptRole
142
+ )
143
+ self.deny = buttons.addButton(
144
+ "Decline" if question else "Deny", QDialogButtonBox.RejectRole
145
+ )
146
+ buttons.accepted.connect(self.allowed)
147
+ buttons.rejected.connect(self.denied)
148
+ layout.addWidget(buttons)
149
+ if self.confirm is not None:
150
+ self.confirm.textChanged.connect(self.check_confirm)
151
+ self.check_confirm()
152
+ model.closed.connect(self.closed_elsewhere)
153
+ model.failed.connect(self.refused)
154
+ self.setMaximumSize(int(room.width() * SCREEN), int(room.height() * SCREEN))
155
+ wanted = self.sizeHint()
156
+ self.resize(
157
+ min(max(WIDTH, wanted.width()), self.maximumWidth()),
158
+ min(wanted.height(), self.maximumHeight()),
159
+ )
160
+
161
+ def check_confirm(self, *_) -> None:
162
+ """A dangerous step: allowed once its device is typed."""
163
+ self.allow.setEnabled(self.confirm.text().strip() == self.approval.confirm)
164
+
165
+ def allowed(self) -> None:
166
+ value = self.value.text().strip() if self.value is not None else None
167
+ self.model.answer(
168
+ self.approval.id,
169
+ True,
170
+ self.words.text().strip(),
171
+ value if value != self.approval.value else None,
172
+ self.choice.currentText() if self.choice is not None else None,
173
+ self.confirm.text().strip() if self.confirm is not None else "",
174
+ )
175
+ self._waiting()
176
+
177
+ def denied(self) -> None:
178
+ self.model.answer(self.approval.id, False, self.words.text().strip())
179
+ self._waiting()
180
+
181
+ def _waiting(self) -> None:
182
+ """The answer travels; the dialog closes when the daemon closes it."""
183
+ for button in (self.allow, self.deny):
184
+ button.setEnabled(False)
185
+
186
+ def closed_elsewhere(self, id: int) -> None:
187
+ if id == self.approval.id:
188
+ self.done(QDialog.Accepted)
189
+
190
+ def refused(self, id: int, why: str) -> None:
191
+ """The daemon did not take the answer (a mistyped value): try again."""
192
+ if id != self.approval.id:
193
+ return
194
+ self.status.setText(why)
195
+ self.status.show()
196
+ self.deny.setEnabled(True)
197
+ if self.confirm is not None:
198
+ self.check_confirm()
199
+ else:
200
+ self.allow.setEnabled(True)
201
+
202
+ def reject(self) -> None:
203
+ """Escape or the close button answers no: an agent never waits on a
204
+ dialog nobody sees."""
205
+ if self.deny.isEnabled():
206
+ self.denied()
207
+
208
+
209
+ class ApprovalPrompts(QObject):
210
+ """Shows what waits for a person, one dialog at a time, in front."""
211
+
212
+ def __init__(self, model: ApprovalsModel, window: QWidget):
213
+ super().__init__(window)
214
+ self.model = model
215
+ self.window = window
216
+ self.queue: Deque[Approval] = deque()
217
+ self.current: Optional[ApprovalDialog] = None
218
+ model.asked.connect(self.asked)
219
+
220
+ def asked(self, approval: Approval) -> None:
221
+ self.queue.append(approval)
222
+ self.show_next()
223
+
224
+ def show_next(self) -> None:
225
+ if self.current is not None:
226
+ return
227
+ while self.queue:
228
+ approval = self.queue.popleft()
229
+ if approval.id in self.model.pending:
230
+ break
231
+ else:
232
+ return
233
+ self.current = ApprovalDialog(approval, self.model, self.window)
234
+ self.current.finished.connect(self.dismissed)
235
+ self.current.show()
236
+ self.window.raise_()
237
+ self.window.activateWindow()
238
+ QApplication.alert(self.window) # the taskbar flashes if the window is behind
239
+
240
+ def dismissed(self, *_) -> None:
241
+ self.current.deleteLater()
242
+ self.current = None
243
+ self.show_next()
thzdaq_gui/ask_box.py ADDED
@@ -0,0 +1,78 @@
1
+ """The small field Ctrl+I opens in an editor, under the line of the cursor:
2
+ the person says in words what code to write there; Enter asks, Esc closes
3
+ (and drops a question on its way). While the assistant writes it says so;
4
+ what went wrong is told under the words. Keys typed in it stay in it: none
5
+ reaches the editor around it."""
6
+
7
+ from PySide6.QtCore import Qt, Signal
8
+ from PySide6.QtWidgets import QFrame, QLabel, QLineEdit, QVBoxLayout, QWidget
9
+
10
+ from thzdaq_gui import theme
11
+
12
+ PLACEHOLDER = "Code to write here, in words (Enter asks, Esc closes)"
13
+ WRITING = "The assistant writes…"
14
+ WIDTH = 520
15
+
16
+
17
+ class AskBox(QFrame):
18
+ asked = Signal(str)
19
+ closed = Signal() # by Esc: a question on its way is dropped
20
+
21
+ def __init__(self, parent: QWidget):
22
+ super().__init__(parent)
23
+ self.setObjectName("ask_box")
24
+ self.setStyleSheet(
25
+ f"#ask_box {{ background: {theme.PANEL};"
26
+ f" border: 1px solid {theme.ACCENT}; border-radius: 4px; }}"
27
+ )
28
+ column = QVBoxLayout(self)
29
+ column.setContentsMargins(4, 4, 4, 4)
30
+ column.setSpacing(2)
31
+ self.field = QLineEdit()
32
+ self.field.setPlaceholderText(PLACEHOLDER)
33
+ self.field.addAction(
34
+ theme.icon("creation", theme.ACCENT), QLineEdit.LeadingPosition
35
+ )
36
+ self.status = QLabel()
37
+ self.status.setWordWrap(True)
38
+ self.status.hide()
39
+ column.addWidget(self.field)
40
+ column.addWidget(self.status)
41
+ self.hide()
42
+
43
+ def open(self, x: int, y: int, width: int) -> None:
44
+ self.field.setReadOnly(False)
45
+ self.status.hide()
46
+ self.setFixedWidth(min(WIDTH, width))
47
+ self.adjustSize()
48
+ self.move(x, y)
49
+ self.show()
50
+ self.raise_()
51
+ self.field.setFocus()
52
+ self.field.selectAll()
53
+
54
+ def _ask(self) -> None:
55
+ asked = self.field.text().strip()
56
+ if asked and not self.field.isReadOnly():
57
+ self.field.setReadOnly(True)
58
+ self.tell(WRITING, theme.MUTED)
59
+ self.asked.emit(asked)
60
+
61
+ def tell(self, text: str, colour: str = theme.BAD) -> None:
62
+ """What happens, or went wrong: the field takes words again after a
63
+ failure."""
64
+ self.field.setReadOnly(colour == theme.MUTED)
65
+ self.status.setText(text)
66
+ self.status.setStyleSheet(f"color: {colour};")
67
+ self.status.show()
68
+ self.adjustSize()
69
+
70
+ def keyPressEvent(self, event) -> None:
71
+ """What the field leaves (Enter, Esc, keys while it is read only):
72
+ taken here, never passed on to the editor."""
73
+ if event.key() in (Qt.Key_Return, Qt.Key_Enter):
74
+ self._ask()
75
+ elif event.key() == Qt.Key_Escape:
76
+ self.hide()
77
+ self.closed.emit()
78
+ event.accept()
@@ -0,0 +1,4 @@
1
+ """The assistant in the window, without Qt: the model's server (provider.py),
2
+ its keys (keys.py), the system prompt (prompt.py) and the loop of a
3
+ conversation with the bench's tools (conversation.py). The view model
4
+ (models/assistant.py) runs it apart from the GUI thread."""
@@ -0,0 +1,106 @@
1
+ """What a person attaches to a message: an image the model sees (a model that
2
+ sees images; the server of one that does not refuses it), a text file whose
3
+ text goes into the message, any other file by its path (a script the
4
+ assistant writes may read it)."""
5
+
6
+ import base64
7
+ import mimetypes
8
+ from dataclasses import dataclass
9
+ from enum import Enum
10
+ from pathlib import Path
11
+ from typing import Any, Dict, List, Optional, Sequence, Union
12
+
13
+ TEXT_BYTES = 256 * 1024 # a longer text file goes by its path
14
+ IMAGE_BYTES = 20 * 1024 * 1024 # what servers take at most, about
15
+ PASTED = "pasted.png"
16
+
17
+ Content = Union[str, List[Dict[str, Any]]] # a message's, as servers take it
18
+
19
+
20
+ class Kind(str, Enum):
21
+ IMAGE = "image"
22
+ TEXT = "text"
23
+ FILE = "file" # by its path
24
+
25
+
26
+ class AttachmentError(Exception):
27
+ """It cannot be attached: why."""
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class Attachment:
32
+ name: str
33
+ kind: Kind
34
+ path: Optional[str] = None # None: pasted
35
+ data: bytes = b"" # an image's
36
+ mime: str = "" # an image's
37
+ text: str = "" # a text file's
38
+
39
+ @staticmethod
40
+ def of_file(path: Union[str, Path]) -> "Attachment":
41
+ """A file as it goes: an image, its text, or its path."""
42
+ path = Path(path)
43
+ try:
44
+ size = path.stat().st_size
45
+ mime = mimetypes.guess_type(path.name)[0] or ""
46
+ if mime.startswith("image/"):
47
+ if size > IMAGE_BYTES:
48
+ raise AttachmentError(f"{path.name}: an image over 20 MB")
49
+ return Attachment.image(path.read_bytes(), path.name, mime, path)
50
+ if size <= TEXT_BYTES:
51
+ text = text_of(path.read_bytes())
52
+ if text is not None:
53
+ return Attachment(path.name, Kind.TEXT, str(path), text=text)
54
+ except OSError as e:
55
+ raise AttachmentError(f"{path.name}: {e.strerror or e}") from None
56
+ if not path.is_file():
57
+ raise AttachmentError(f"{path.name}: not a file")
58
+ return Attachment(path.name, Kind.FILE, str(path))
59
+
60
+ @staticmethod
61
+ def image(
62
+ data: bytes,
63
+ name: str = PASTED,
64
+ mime: str = "image/png",
65
+ path: Optional[Path] = None,
66
+ ) -> "Attachment":
67
+ return Attachment(
68
+ name, Kind.IMAGE, str(path) if path else None, data=data, mime=mime
69
+ )
70
+
71
+ def told(self) -> str:
72
+ """What the message says of it in words."""
73
+ where = f" ({self.path})" if self.path else ""
74
+ if self.kind is Kind.TEXT:
75
+ return f"Attached file {self.name}{where}:\n```\n{self.text}\n```"
76
+ if self.kind is Kind.FILE:
77
+ return f"Attached file {self.name}{where}: read it from there"
78
+ return f"Attached image {self.name}{where}"
79
+
80
+ def part(self) -> Dict[str, Any]:
81
+ """An image as a part of the message."""
82
+ encoded = base64.b64encode(self.data).decode("ascii")
83
+ return {
84
+ "type": "image_url",
85
+ "image_url": {"url": f"data:{self.mime};base64,{encoded}"},
86
+ }
87
+
88
+
89
+ def text_of(data: bytes) -> Optional[str]:
90
+ """The text of a file; None for one that is not text."""
91
+ if b"\0" in data:
92
+ return None
93
+ try:
94
+ return data.decode("utf-8")
95
+ except UnicodeDecodeError:
96
+ return None
97
+
98
+
99
+ def content(text: str, attachments: Sequence[Attachment]) -> Content:
100
+ """A person's message with what is attached: words alone without images,
101
+ parts (the words, then each image) with them."""
102
+ words = "\n\n".join([text, *(a.told() for a in attachments)]).strip()
103
+ images = [a.part() for a in attachments if a.kind is Kind.IMAGE]
104
+ if not images:
105
+ return words
106
+ return [{"type": "text", "text": words}, *images]