-
Notifications
You must be signed in to change notification settings - Fork 5
/
app.py
2203 lines (1811 loc) · 74.3 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import faulthandler
import json
import math
import os
import random
import re
import sys
import uuid
from abc import ABC
from abc import abstractmethod
from collections import deque
from os import linesep
from pathlib import Path
import keyring
import mistune
import requests
from litellm import completion
from PyQt6.QtCore import (
pyqtProperty,
)
from PyQt6.QtCore import pyqtSignal
from PyQt6.QtCore import QEasingCurve
from PyQt6.QtCore import QEvent
from PyQt6.QtCore import QObject
from PyQt6.QtCore import QPoint
from PyQt6.QtCore import QPointF
from PyQt6.QtCore import QPropertyAnimation
from PyQt6.QtCore import QRect
from PyQt6.QtCore import QRectF
from PyQt6.QtCore import QRunnable
from PyQt6.QtCore import QSettings
from PyQt6.QtCore import QSize
from PyQt6.QtCore import QSizeF
from PyQt6.QtCore import Qt
from PyQt6.QtCore import QThreadPool
from PyQt6.QtCore import QTimer
from PyQt6.QtGui import QAction
from PyQt6.QtGui import QBrush
from PyQt6.QtGui import QColor
from PyQt6.QtGui import QCursor
from PyQt6.QtGui import QFont
from PyQt6.QtGui import QFontMetrics
from PyQt6.QtGui import QIcon
from PyQt6.QtGui import QKeyEvent
from PyQt6.QtGui import QKeySequence
from PyQt6.QtGui import QPainter
from PyQt6.QtGui import QPen
from PyQt6.QtGui import QPolygonF
from PyQt6.QtGui import QTextDocument
from PyQt6.QtGui import QTransform
from PyQt6.QtWidgets import QApplication
from PyQt6.QtWidgets import QComboBox
from PyQt6.QtWidgets import QDialog
from PyQt6.QtWidgets import QFileDialog
from PyQt6.QtWidgets import QGraphicsEllipseItem
from PyQt6.QtWidgets import QGraphicsItem
from PyQt6.QtWidgets import QGraphicsItemGroup
from PyQt6.QtWidgets import QGraphicsLinearLayout
from PyQt6.QtWidgets import QGraphicsPolygonItem
from PyQt6.QtWidgets import QGraphicsProxyWidget
from PyQt6.QtWidgets import QGraphicsRectItem
from PyQt6.QtWidgets import QGraphicsScene
from PyQt6.QtWidgets import QGraphicsView
from PyQt6.QtWidgets import QGraphicsWidget
from PyQt6.QtWidgets import QHBoxLayout
from PyQt6.QtWidgets import QLabel
from PyQt6.QtWidgets import QLineEdit
from PyQt6.QtWidgets import QListWidget
from PyQt6.QtWidgets import QListWidgetItem
from PyQt6.QtWidgets import QMainWindow
from PyQt6.QtWidgets import QMenu
from PyQt6.QtWidgets import QMessageBox
from PyQt6.QtWidgets import QProgressBar
from PyQt6.QtWidgets import QPushButton
from PyQt6.QtWidgets import QRubberBand
from PyQt6.QtWidgets import QScrollBar
from PyQt6.QtWidgets import QSizePolicy
from PyQt6.QtWidgets import QTextEdit
from PyQt6.QtWidgets import QVBoxLayout
from PyQt6.QtWidgets import QWidget
faulthandler.enable()
faulthandler.dump_traceback(open("crash.log", "w"))
APPLICATION_TITLE = "Chat Circuit"
def resource_path(relative_path):
"""Get absolute path to resource, works for dev and for PyInstaller"""
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
def load_models_from_config(config_file="models.conf"):
config_path = os.path.join(os.path.dirname(__file__), config_file)
try:
with open(config_path) as f:
models = [line.strip() for line in f if line.strip()]
except FileNotFoundError:
print(f"Config file {config_file} not found. Using default models.")
models = [
"llama3:latest",
"mistral:latest",
"tinyllama:latest",
]
return models
LLM_MODELS = load_models_from_config()
DEFAULT_LLM_MODEL = LLM_MODELS[0]
thread_pool = QThreadPool()
active_workers = 0
class CustomFilePicker(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
main_layout = QHBoxLayout()
main_layout.setSpacing(0)
main_layout.setContentsMargins(0, 0, 0, 0)
button_style = """
background-color: #F0F0F0;
text-align: center;
border: 1px solid #808080;
font-size: 18px;
"""
self.selected_file_paths = []
self.file_count_button = QPushButton("0")
self.file_count_button.setFixedSize(28, 26)
self.file_count_button.setStyleSheet(button_style + "border-right: none;")
self.file_count_button.clicked.connect(self.show_file_list)
self.attach_file_button = QPushButton()
self.attach_file_button.setIcon(QIcon.fromTheme("mail-attachment"))
self.attach_file_button.setStyleSheet(button_style + "border-left: none;")
self.attach_file_button.clicked.connect(self.open_file_dialog)
self.attach_file_button.setFixedSize(28, 26)
main_layout.addWidget(self.file_count_button)
main_layout.addWidget(self.attach_file_button)
self.setLayout(main_layout)
def get_selected_files(self):
return self.selected_file_paths
def set_selected_files(self, files):
self.selected_file_paths = files
self.update_file_count()
def update_file_count(self):
self.file_count_button.setText(str(len(self.selected_file_paths)))
def open_file_dialog(self):
file_dialog = QFileDialog(None)
file_dialog.setWindowFlags(Qt.WindowType.FramelessWindowHint)
file_dialog.setWindowTitle("Select a File")
file_dialog.setFileMode(QFileDialog.FileMode.ExistingFile)
if file_dialog.exec():
selected_file = file_dialog.selectedFiles()[0]
if selected_file not in self.selected_file_paths:
self.selected_file_paths.append(selected_file)
self.update_file_count()
def show_file_list(self):
if self.selected_file_paths:
file_list_dialog = QDialog(None)
file_list_dialog.setWindowFlags(
Qt.WindowType.FramelessWindowHint | Qt.WindowType.Tool
)
dialog_layout = QVBoxLayout(file_list_dialog)
dialog_layout.setContentsMargins(0, 0, 0, 0)
dialog_layout.setSpacing(0)
file_list_widget = QListWidget()
file_list_widget.setStyleSheet("""
QListWidget {
border: none;
outline: none;
background-color: white;
}
QListWidget::item {
border: none;
padding: 0;
height: 30px;
}
QListWidget::item:selected {
background: transparent;
}
""")
for file_path in self.selected_file_paths:
file_name = os.path.basename(file_path)
file_item_widget = QWidget()
file_item_layout = QHBoxLayout(file_item_widget)
file_item_layout.setContentsMargins(5, 0, 5, 0)
file_item_layout.setSpacing(5)
remove_file_button = QPushButton("×")
remove_file_button.setFixedSize(20, 20)
remove_file_button.setStyleSheet("""
QPushButton {
border: none;
background-color: transparent;
color: red;
font-weight: bold;
font-size: 18px;
}
QPushButton:hover {
color: darkred;
}
""")
remove_file_button.clicked.connect(
lambda _, path=file_path: self.remove_file(path, file_list_widget)
)
file_name_label = QLabel(file_name)
file_name_label.setStyleSheet("""
color: #333;
background: transparent;
border: none;
font-size: 13px;
""")
file_item_layout.addWidget(remove_file_button)
file_item_layout.addWidget(file_name_label, 1)
file_list_item = QListWidgetItem(file_list_widget)
file_list_widget.addItem(file_list_item)
file_list_widget.setItemWidget(file_list_item, file_item_widget)
dialog_layout.addWidget(file_list_widget)
file_list_dialog.setLayout(dialog_layout)
item_height = 30 # This should match the height in the CSS
num_items = len(self.selected_file_paths)
calculated_height = num_items * item_height
max_height = 300
dialog_height = min(calculated_height, max_height)
# Set the fixed width and calculated height
file_list_dialog.setFixedSize(300, dialog_height)
self.dialog = file_list_dialog
self.update_list_position(calculated_height)
class ClickOutsideFilter(QObject):
def __init__(self, dialog):
super().__init__()
self.dialog = dialog
def eventFilter(self, obj, event):
if event.type() == QEvent.Type.Leave and obj == self.dialog:
if not self.dialog.geometry().contains(QCursor.pos()):
self.dialog.close()
return True
return False
click_outside_filter = ClickOutsideFilter(file_list_dialog)
file_list_dialog.installEventFilter(click_outside_filter)
file_list_dialog.activateWindow()
file_list_dialog.raise_()
file_list_dialog.exec()
file_list_dialog.removeEventFilter(click_outside_filter)
def remove_file(self, file_path, file_list_widget):
if file_path in self.selected_file_paths:
index = self.selected_file_paths.index(file_path)
del self.selected_file_paths[index]
self.update_file_count()
file_list_widget.takeItem(index)
def update_list_position(self, list_height: int):
file_count_button_pos = self.file_count_button.mapToGlobal(
self.file_count_button.rect().topLeft()
)
self.dialog.move(
file_count_button_pos.x(), file_count_button_pos.y() - list_height
)
class CommandInvoker:
def __init__(self):
self.history = []
self.redo_stack = []
def execute(self, command):
command.execute()
self.history.append(command)
self.redo_stack.clear()
def undo(self):
if self.history:
command = self.history.pop()
command.undo()
self.redo_stack.append(command)
def redo(self):
if self.redo_stack:
command = self.redo_stack.pop()
command.execute()
self.history.append(command)
def create_svg_icon(file_path):
icon = QIcon(file_path)
return icon
def create_button(icon_path, tooltip, callback):
button_widget = QGraphicsProxyWidget()
button = QPushButton()
button.setStyleSheet(
"""
QPushButton {
border: 1px solid #808080;
}
"""
)
icon = create_svg_icon(icon_path)
button.setIcon(icon)
button.setIconSize(QSize(24, 24))
button.setToolTip(tooltip)
button.clicked.connect(callback)
button_widget.setWidget(button)
return button_widget
def add_buttons(form_widget, picker):
bottom_layout = QGraphicsLinearLayout(Qt.Orientation.Horizontal)
# Define button configurations
buttons = [
(resource_path("resources/ripple.svg"), "Re-Run", form_widget.re_run_all),
(resource_path("resources/fork.svg"), "Fork", form_widget.clone_form),
(
resource_path("resources/clone.svg"),
"Clone Branch",
form_widget.clone_branch,
),
(
resource_path("resources/bulb.svg"),
"Follow-up Questions",
form_widget.generate_follow_up_questions,
),
(resource_path("resources/delete.svg"), "Delete", form_widget.delete_form),
]
picker_widget = QGraphicsProxyWidget()
picker_widget.setWidget(picker)
bottom_layout.addItem(picker_widget)
# Create and add buttons
for icon_path, tooltip, callback in buttons:
button_widget = create_button(icon_path, tooltip, callback)
bottom_layout.addItem(button_widget)
return bottom_layout
class Command(ABC):
@abstractmethod
def execute(self):
pass
@abstractmethod
def undo(self):
pass
class CreateFormCommand(Command):
def __init__(self, scene, parent_form=None, position=None, model=DEFAULT_LLM_MODEL):
self.scene = scene
self.parent_form = parent_form
self.model = model
self.created_form = None
self.position = position
self.link_line = None
def execute(self):
self.created_form = FormWidget(parent=self.parent_form, model=self.model)
self.scene.addItem(self.created_form)
if self.position:
self.created_form.setPos(self.position)
if self.parent_form:
self.parent_form.child_forms.append(self.created_form)
self.link_line = LinkLine(self.parent_form, self.created_form)
self.scene.addItem(self.link_line)
self.created_form.link_line = self.link_line
def undo(self):
if self.created_form:
if self.created_form.scene() == self.scene:
self.scene.removeItem(self.created_form)
if self.parent_form and self.created_form in self.parent_form.child_forms:
self.parent_form.child_forms.remove(self.created_form)
if self.link_line and self.link_line.scene() == self.scene:
self.scene.removeItem(self.link_line)
self.created_form = None
self.link_line = None
class DeleteFormCommand(Command):
def __init__(self, form):
self.form = form
self.parent_form = form.parent_form
self.child_forms = form.child_forms[:]
self.link_line = form.link_line
self.scene = form.scene()
self.pos = form.pos()
self.deleted_subtree = []
def execute(self):
self.deleted_subtree = self._delete_subtree(self.form)
if self.parent_form and self.form in self.parent_form.child_forms:
self.parent_form.child_forms.remove(self.form)
def undo(self):
self._restore_subtree(self.deleted_subtree)
if self.parent_form:
self.parent_form.child_forms.append(self.form)
def _delete_subtree(self, form):
deleted = []
for child in form.child_forms[:]:
deleted.extend(self._delete_subtree(child))
if form.scene() == self.scene:
self.scene.removeItem(form)
if form.link_line and form.link_line.scene() == self.scene:
self.scene.removeItem(form.link_line)
deleted.append((form, form.pos(), form.link_line))
return deleted
def _restore_subtree(self, deleted_items):
for form, pos, link_line in reversed(deleted_items):
self.scene.addItem(form)
form.setPos(pos)
if link_line:
self.scene.addItem(link_line)
form.link_line = link_line
class MoveFormCommand(Command):
def __init__(self, form, old_pos, new_pos):
self.form = form
self.old_pos = old_pos
self.new_pos = new_pos
def execute(self):
self.form.setPos(self.new_pos)
if self.form.link_line:
self.form.link_line.update_position()
def undo(self):
self.form.setPos(self.old_pos)
if self.form.link_line:
self.form.link_line.update_position()
class CloneBranchCommand(Command):
def __init__(self, scene, source_form):
self.scene = scene
self.source_form = source_form
self.cloned_forms = []
self.parent_form = None
def execute(self):
self.parent_form = self.source_form.parent_form
new_pos = self.source_form.pos() + QPointF(200, 600) # Offset the new branch
self.cloned_forms = self._clone_branch(
self.source_form, self.parent_form, new_pos
)
def undo(self):
for form in self.cloned_forms:
if form.scene() == self.scene:
self.scene.removeItem(form)
if form.link_line and form.link_line.scene() == self.scene:
self.scene.removeItem(form.link_line)
if self.parent_form:
self.parent_form.child_forms = [
f for f in self.parent_form.child_forms if f not in self.cloned_forms
]
def _clone_branch(self, source_form, parent_form, position):
cloned_form = FormWidget(parent=parent_form, model=source_form.model)
cloned_form.setPos(position)
cloned_form.input_box.widget().setPlainText(
source_form.input_box.widget().toPlainText()
)
cloned_form.conversation_area.widget().setPlainText(
source_form.conversation_area.widget().toPlainText()
)
self.scene.addItem(cloned_form)
if parent_form:
parent_form.child_forms.append(cloned_form)
link_line = LinkLine(parent_form, cloned_form)
self.scene.addItem(link_line)
cloned_form.link_line = link_line
cloned_forms = [cloned_form]
for child in source_form.child_forms:
child_pos = cloned_form.pos() + (child.pos() - source_form.pos())
cloned_forms.extend(self._clone_branch(child, cloned_form, child_pos))
return cloned_forms
class HeaderWidget(QGraphicsWidget):
model_changed = pyqtSignal(str)
def __init__(self, model_name):
super().__init__()
self.model_dropdown = QComboBox()
self.progress_bar = QProgressBar()
self.model_name = model_name
self.is_initialized = False
self.setMinimumHeight(30) # Reduced height
self.setMaximumHeight(30)
QTimer.singleShot(0, self.create_widgets)
def create_widgets(self):
container = QWidget()
main_layout = QVBoxLayout(container)
main_layout.setContentsMargins(0, 0, 0, 0)
main_layout.setSpacing(0)
self.model_dropdown.addItems(LLM_MODELS)
self.model_dropdown.setStyleSheet(
"""
QComboBox {
background-color: #2c3e50;
color: #ecf0f1;
border: 1px solid #34495e;
border-radius: 3px;
padding: 5px 25px 5px 5px;
min-height: 20px;
}
QComboBox::drop-down {
subcontrol-origin: padding;
subcontrol-position: top right;
width: 20px;
border-left: 1px solid #34495e;
border-top-right-radius: 3px;
border-bottom-right-radius: 3px;
}
QComboBox::down-arrow {
image: none; /* Remove default arrow image */
width: 10px;
height: 15px;
margin-right: 5px;
}
QComboBox::down-arrow:on {
top: 1px;
left: 1px;
}
QComboBox::down-arrow::after {
content: "";
display: block;
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 5px solid #ecf0f1; /* Arrow color */
}
QComboBox QAbstractItemView {
background-color: #34495e;
color: #ecf0f1;
selection-background-color: #3498db;
}
"""
)
self.model_dropdown.currentTextChanged.connect(self.on_model_changed)
main_layout.addWidget(self.model_dropdown)
self.progress_bar.setRange(0, 0)
self.progress_bar.setTextVisible(False)
self.progress_bar.setFixedHeight(3)
self.progress_bar.setStyleSheet(
"""
QProgressBar {
background-color: #ecf0f1;
border: none;
border-radius: 1px;
}
QProgressBar::chunk {
background-color: #e74c3c;
border-radius: 1px;
}
"""
)
self.progress_bar.hide()
main_layout.addWidget(self.progress_bar)
proxy = QGraphicsProxyWidget(self)
proxy.setWidget(container)
layout = QGraphicsLinearLayout(Qt.Orientation.Vertical)
layout.setContentsMargins(0, 0, 0, 0)
layout.addItem(proxy)
self.setLayout(layout)
self.is_initialized = True
self.update_model_name()
def start_processing(self):
if self.is_initialized and self.progress_bar:
self.progress_bar.show()
def stop_processing(self):
if self.is_initialized and self.progress_bar:
self.progress_bar.hide()
def on_model_changed(self, new_model):
self.model_name = new_model
self.model_changed.emit(new_model)
def update_model_name(self):
if self.is_initialized and self.model_dropdown:
self.model_dropdown.setCurrentText(self.model_name)
class CircleAnimator(QObject):
def __init__(self):
super().__init__()
self._scale = 1.0
@pyqtProperty(float)
def scale(self):
return self._scale
@scale.setter
def scale(self, value):
self._scale = value
class HoverCircle(QGraphicsEllipseItem):
def __init__(self, parent=None):
super().__init__(parent)
self.setAcceptHoverEvents(True)
self.setFlag(QGraphicsItem.GraphicsItemFlag.ItemIsMovable, True)
self.normal_radius = 10
self.hover_radius = 30
self.setBrush(QBrush(QColor(70, 130, 180)))
self.setPen(QPen(Qt.PenStyle.NoPen))
self.setRect(-10, -10, self.normal_radius * 2, self.normal_radius * 2)
self.animator = CircleAnimator()
self.animation = QPropertyAnimation(self.animator, b"scale")
self.animation.setDuration(200)
self.animation.valueChanged.connect(self.update_scale)
self.setAcceptedMouseButtons(Qt.MouseButton.LeftButton)
self.dragging = False
def mousePressEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
self.dragging = True
self.drag_start_pos = event.scenePos()
event.accept()
else:
super().mousePressEvent(event)
def mouseMoveEvent(self, event):
if self.dragging:
new_pos = event.scenePos() - self.drag_start_pos
self.parentItem().moveBy(new_pos.x(), new_pos.y())
self.drag_start_pos = event.scenePos()
event.accept()
else:
super().mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
self.dragging = False
event.accept()
else:
super().mouseReleaseEvent(event)
def update_scale(self, scale):
center = self.rect().center()
new_radius = self.normal_radius * scale
new_rect = QRectF(0, 0, new_radius * 2, new_radius * 2)
new_rect.moveCenter(center)
self.setRect(new_rect)
def hoverEnterEvent(self, event):
self.animation.setStartValue(1.0)
self.animation.setEndValue(self.hover_radius / self.normal_radius)
self.animation.setEasingCurve(QEasingCurve.Type.OutQuad)
self.animation.start()
def hoverLeaveEvent(self, event):
self.animation.setStartValue(self.hover_radius / self.normal_radius)
self.animation.setEndValue(1.0)
self.animation.setEasingCurve(QEasingCurve.Type.OutQuad)
self.animation.start()
class LinkLine(QGraphicsItemGroup):
def __init__(self, parent, child):
super().__init__()
self.parent = parent
self.child = child
self.chevrons = []
self.chevron_color = QColor(0, 158, 115)
self.chevron_size = 10
self.chevron_spacing = 30
self.setZValue(-1)
self.update_position()
def create_chevron(self, pos, angle):
chevron = QGraphicsPolygonItem(self)
chevron.setBrush(self.chevron_color)
chevron.setPen(QPen(self.chevron_color, 1))
# Create chevron points
p1 = QPointF(-self.chevron_size / 2, -self.chevron_size / 2)
p2 = QPointF(self.chevron_size / 2, 0)
p3 = QPointF(-self.chevron_size / 2, self.chevron_size / 2)
chevron.setPolygon(QPolygonF([p1, p2, p3]))
chevron.setPos(pos)
chevron.setRotation(math.degrees(angle))
return chevron
def update_position(self):
parent_center = self.parent.mapToScene(self.parent.boundingRect().center())
child_center = self.child.mapToScene(self.child.boundingRect().center())
# Calculate the direction vector
dx = child_center.x() - parent_center.x()
dy = child_center.y() - parent_center.y()
length = math.sqrt(dx**2 + dy**2)
# Clear existing chevrons
for chevron in self.chevrons:
self.removeFromGroup(chevron)
self.chevrons.clear()
if length == 0:
return
# Normalize the direction vector
dx, dy = dx / length, dy / length
# Calculate angle for chevrons
angle = math.atan2(dy, dx)
# Create chevrons along the line
num_chevrons = int(length / self.chevron_spacing)
for i in range(num_chevrons):
pos = QPointF(
parent_center.x() + dx * (i + 0.5) * self.chevron_spacing,
parent_center.y() + dy * (i + 0.5) * self.chevron_spacing,
)
chevron = self.create_chevron(pos, angle)
self.addToGroup(chevron)
self.chevrons.append(chevron)
class HtmlRenderer(mistune.HTMLRenderer):
def __init__(self):
super().__init__()
self.text_document = QTextDocument()
def render(self, text):
markdown = mistune.create_markdown(renderer=self)
html = markdown(text)
self.text_document.setHtml(html)
return self.text_document
class LlmWorkerSignals(QObject):
update = pyqtSignal(str)
finished = pyqtSignal()
notify_child = pyqtSignal()
error = pyqtSignal(str)
class LlmWorker(QRunnable):
def __init__(self, model, system_message, messages):
super().__init__()
self.model = model
self.messages = messages
self.system_message = system_message or "You are a helpful assistant."
self.signals = LlmWorkerSignals()
def run(self):
try:
formatted_messages = []
if self.system_message:
formatted_messages.append(
{"role": "system", "content": self.system_message}
)
formatted_messages.extend(self.messages)
response = completion(
model=f"{self.model}",
messages=formatted_messages,
api_base="http://localhost:11434",
)
content = response.choices[0].message.content
self.signals.update.emit(content)
self.signals.finished.emit()
except Exception as e:
self.signals.error.emit(str(e))
finally:
self.signals.notify_child.emit()
class JinaReaderWorkerSignals(QObject):
result = pyqtSignal(str)
error = pyqtSignal(str)
class JinaReaderWorker(QRunnable):
def __init__(self, url, jina_api_key):
super().__init__()
self.url = url
self.jina_api_key = jina_api_key
self.signals = JinaReaderWorkerSignals()
def run(self):
try:
jina_url = f"https://r.jina.ai/{self.url}"
headers = {"Authorization": f"Bearer {self.jina_api_key}"}
response = requests.get(jina_url, headers=headers)
response.raise_for_status()
content = response.text
self.signals.result.emit(content)
except Exception as e:
self.signals.error.emit(str(e))
class ResizeHandle(QGraphicsWidget):
resize_signal = pyqtSignal(QPointF)
def __init__(self, parent=None):
super().__init__(parent)
self.setFlag(QGraphicsWidget.GraphicsItemFlag.ItemIsMovable, False)
self.setFlag(QGraphicsWidget.GraphicsItemFlag.ItemIsSelectable, False)
self.setCursor(QCursor(Qt.CursorShape.SizeFDiagCursor))
self.setZValue(2)
self.setGeometry(QRectF(0, 0, 10, 10))
self.initial_pos = QPointF()
self.initial_size = QSizeF()
self.resizing = False
def mousePressEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
self.resizing = True
self.initial_pos = event.scenePos()
parent = self.parentItem()
if isinstance(parent, FormWidget):
self.initial_size = parent.size()
event.accept()
else:
event.ignore()
def mouseMoveEvent(self, event):
if self.resizing:
delta = event.scenePos() - self.initial_pos
new_width = max(
self.initial_size.width() + delta.x(), self.parentItem().minimumWidth()
)
new_height = max(
self.initial_size.height() + delta.y(),
self.parentItem().minimumHeight(),
)
self.resize_signal.emit(QPointF(new_width, new_height))
event.accept()
else:
event.ignore()
def mouseReleaseEvent(self, event):
if self.resizing:
self.resizing = False
event.accept()
else:
event.ignore()
def paint(self, painter, option, widget):
painter.setBrush(QBrush(QColor(Qt.GlobalColor.darkGray).lighter(128)))
painter.setPen(QPen(Qt.GlobalColor.darkGray, 2))
painter.drawRect(self.boundingRect())
class FormWidget(QGraphicsWidget):
def __init__(self, parent=None, model=None):
super().__init__()
# LLM
self.model = model
self.system_message = "You are a helpful assistant."
self.setFlag(QGraphicsItem.GraphicsItemFlag.ItemIsMovable)
self.setFlag(QGraphicsItem.GraphicsItemFlag.ItemIsSelectable)
self.setFlag(QGraphicsItem.GraphicsItemFlag.ItemIsFocusable)
self.parent_form = parent
self.child_forms = []
self.link_line = None
# Re-Run all form nodes
self.llm_worker = None
self.jina_worker = None
self.form_chain = deque()
# Create main layout
self.main_layout = QGraphicsLinearLayout(Qt.Orientation.Vertical)
# Create and add header
self.header = HeaderWidget(self.model)
self.header.model_changed.connect(self.on_model_changed)
self.header.setZValue(1)
self.main_layout.addItem(self.header)
self.header.update_model_name()
# Create chat layout
chat_layout = QGraphicsLinearLayout(Qt.Orientation.Vertical)
# Conversation area
self.markdown_content = ""
self.custom_font = QFont("Fantasque Sans Mono", 18)
self.conversation_area = QGraphicsProxyWidget()
conversation_widget = QTextEdit()
conversation_widget.setReadOnly(True)
conversation_widget.setAcceptRichText(True)
conversation_widget.setStyleSheet(
f"""
QTextEdit {{
background-color: white;
border: 1px solid #ccc;
font-family: {self.custom_font.family()};
font-size: {self.custom_font.pointSize()}pt;
}}
"""
)
self.conversation_area.setWidget(conversation_widget)
chat_layout.addItem(self.conversation_area)
self.conversation_area.widget().setContextMenuPolicy(
Qt.ContextMenuPolicy.CustomContextMenu
)
self.conversation_area.widget().customContextMenuRequested.connect(
self.show_context_menu
)
# Create a horizontal layout for emoji and input box
input_layout = QGraphicsLinearLayout(Qt.Orientation.Horizontal)
# Input box
self.input_box = QGraphicsProxyWidget()
self.input_text_edit = QTextEdit()
self.input_text_edit.setPlaceholderText(
"Prompt (and press Ctrl+Enter to submit)"
)
self.input_text_edit.setMinimumHeight(30)
self.input_text_edit.setSizePolicy(
QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum
)
self.input_text_edit.textChanged.connect(self.adjust_input_box_height)
self.input_box.setWidget(self.input_text_edit)
self.input_box.setSizePolicy(
QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum
)
# Connect the key press event
self.input_text_edit.installEventFilter(self)
input_layout.addItem(self.input_box)