-
Notifications
You must be signed in to change notification settings - Fork 1
/
CSyntaxParser4.py
2920 lines (2212 loc) · 113 KB
/
CSyntaxParser4.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 ast
import math
from typing import Any, Union
import astor
import re
import queue
import os
import textwrap
import json
import tkinter as tk
from tkinter import ttk
from tkinter.scrolledtext import ScrolledText
# Cause Process.start re imports everything in alternative cpu core and that basically reruns global code
import ChatGPT
from html import escape
from tkhtmlview import HTMLLabel
from tkinter import Tk, Button, filedialog
import cssutils
from bs4 import BeautifulSoup
import fitz # PyMuPDF
from PIL import Image, ImageTk
import base64
import os
import threading
import time
def runFunctionCatchExceptions(func, *args, **kwargs):
try:
result = func(*args, **kwargs)
except Exception as e:
return ["exception", e]
return ["RESULT", result]
def runFunctionWithTimeoutAndRetry(func, args=(), kwargs={}, timeout_duration=10, default=None, retry_count=3):
class InterruptableThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.result = default
def run(self):
self.result = runFunctionCatchExceptions(func, *args, **kwargs)
it = InterruptableThread()
it.start()
it.join(timeout_duration)
if it.is_alive():
print("Function did not complete within the timeout.")
for attempt in range(retry_count):
it = InterruptableThread()
it.start()
it.join(timeout_duration)
if not it.is_alive():
break
print(f"Attempt {attempt + 1} timed out, retrying...")
if it.is_alive():
return default
if it.result[0] == "exception":
raise it.result[1]
return it.result[1]
def extract_html_content(html_content):
# Check if the input contains HTML tags
if "<html>" not in html_content and "</html>" not in html_content:
# No HTML tags found, return the plaintext content
return [html_content],{}
# Parse HTML content
soup = BeautifulSoup(html_content, 'html.parser')
# Find all <p> tags and extract their content
paragraphs = [p.get_text() for p in soup.find_all('p')]
# Find all <h*> tags and extract their content
headings = {}
for i in range(1, 7): # H1 to H6
h_tags = soup.find_all(f'h{i}')
headings[f'h{i}_headings'] = [h.get_text() for h in h_tags]
# Return extracted content
return paragraphs, headings
def inline_css(html_content):
# Find the CSS styles within the HTML content
soup = BeautifulSoup(html_content, 'html.parser')
style_tag = soup.find('style')
if style_tag:
try:
# Parse the CSS styles
css_styles = cssutils.parseString(style_tag.string)
except cssutils.CSSParseException as e:
print(f"Error parsing CSS: {e}")
return html_content
# Remove the original <style> tag
style_tag.decompose()
# Inline the CSS styles into the HTML content
for rule in css_styles:
if rule.type == rule.STYLE_RULE:
styles = rule.style
css_text = styles.getCssText()
for selector in rule.selectorList:
# Find all HTML elements matching the selector
elements = soup.select(selector.selectorText)
for element in elements:
# Inline the styles into the element
element['style'] = f"{css_text}; {element.get('style', '')}"
return str(soup)
from transformers import BertTokenizer, BertModel
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
# Instantiate the Sentence Transformer model
model = SentenceTransformer('bert-base-nli-mean-tokens')
def get_bert_embeddings(passages):
"""
Get BERT embeddings for a list of passages or a single passage.
Args:
passages (str or list of str): Passage(s) to encode into embeddings.
Returns:
embeddings (numpy array or list of numpy arrays): BERT embeddings for each passage.
"""
if isinstance(passages, str): # Check if passages is a single string
passages = [passages] # Convert to a list with one element
embeddings = model.encode(passages)
return embeddings
def calculate_cosine_similarity(embeddings1, embeddings2):
"""
Calculate cosine similarity between two sets of embeddings.
Args:
embeddings1 (numpy array): Embeddings for the first set of passages.
embeddings2 (numpy array): Embeddings for the second set of passages.
Returns:
similarity_scores (numpy array): Cosine similarity scores between corresponding pairs of embeddings.
"""
similarity_scores = cosine_similarity(embeddings1, embeddings2)
return similarity_scores
def calculate_similarity_between_passages(passage1, passage2):
"""
Calculate similarity between two passages.
Args:
passage1 (str): First passage.
passage2 (str): Second passage.
Returns:
similarity_score (float): Cosine similarity score between the two passages.
"""
# Get BERT embeddings for the passages
embeddings = get_bert_embeddings([passage1, passage2])
# Calculate cosine similarity between the embeddings
similarity_score = calculate_cosine_similarity(embeddings[0:1], embeddings[1:2])
return similarity_score[0][0]
import time
from queue import Queue
from threading import Thread
import sys
import multiprocessing as mp
def clear_console():
os.system('cls' if os.name == 'nt' else 'clear')
JARVIS_ACCEPT="AudioFiles/Jarvis_Accept.wav"
JARVIS_CLICK="AudioFiles/Jarvis_Click.wav"
JARVIS_PROCESSING="AudioFiles/Load/Jarvis_Load_out.wav"
JARVIS_START="AudioFiles/Jarvis_StartUp.wav"
import sounddevice as sd
from scipy.io.wavfile import read
import numpy as np
def play_audio(file_path):
# Read the audio file
sample_rate, data = read(file_path)
# Normalize the audio data
data = data.astype(np.float32) / np.max(np.abs(data), axis=0)
# Play the audio
sd.play(data, sample_rate)
"""
class SophiaAssistant:
def __init__(self):
self.recorder = AudioToTextRecorder(
spinner=False,
model='small.en',
language='en',
on_wakeword_detected=lambda: ( play_audio(JARVIS_START),print("Wake Word detected"),self.start_callback()),
on_recording_stop=lambda: ( play_audio(JARVIS_PROCESSING), self.recording_stopped()),
on_wakeword_timeout=lambda:(play_audio(JARVIS_PROCESSING),print("Deactivated cause no audio")),
on_recording_start=lambda: print("Speak, we're listening now"),
enable_realtime_transcription=True,
on_realtime_transcription_update=self.realtime_transcribed_update,
on_realtime_transcription_stabilized=self.realtime_transcribed_update_stabilized,
silero_sensitivity=0.4,
silero_use_onnx=True,
webrtc_sensitivity=2,
post_speech_silence_duration=1.5,
min_length_of_recording=0,
min_gap_between_recordings=0,
realtime_processing_pause=0.2,
realtime_model_type='tiny.en',
wake_words='jarvis'
)
self.is_turned_on = False
self.message_queues = {
'RecordingStart': Queue(),
'RecordingStop': Queue(),
'TranscriptionUpdate': Queue(),
'TranscriptionStabilized': Queue(),
'ProcessedText': Queue(),
}
self.curr_message = {
'RecordingStart': '',
'RecordingStop': '',
'TranscriptionUpdate': '',
'TranscriptionStabilized': '',
'ProcessedText': '',
}
self.loop_thread = Thread(target=self._turn_on_loop)
self.loop_thread.start() # Start the thread
# Callback functions
self.start_callback = None
self.stop_callback = None
self.transcription_update_callback = None
self.transcription_stabilized_callback = None
self.processed_text_callback = None
self.current_transcription_update = ""
self.current_transcription_stabilized = ""
def recording_started(self, *args, **kwargs):
text = args[0] if args else ""
self.message_queues['RecordingStart'].put(f"Recording started: {text}")
self.curr_message['RecordingStart'] = f"Recording started: {text}"
if self.start_callback:
self.start_callback(text)
def realtime_transcribed_update(self, *args, **kwargs):
text = args[0] if args else ""
if self.is_turned_on:
self.current_transcription_update = f"Real-time transcription update: {text}"
self.curr_message['TranscriptionUpdate'] = self.current_transcription_update
# If callback is set, update it
if self.transcription_update_callback:
self.transcription_update_callback(self.current_transcription_update)
def realtime_transcribed_update_stabilized(self, *args, **kwargs):
text = args[0] if args else ""
if self.is_turned_on:
self.current_transcription_stabilized = f"Real-time transcription stabilized: {text}"
self.curr_message['TranscriptionStabilized'] = self.current_transcription_stabilized
# If callback is set, update it
if self.transcription_stabilized_callback:
self.transcription_stabilized_callback(self.current_transcription_stabilized)
def recording_stopped(self, *args, **kwargs):
text = args[0] if args else ""
# If turned on, put the current updates into the queue
if self.is_turned_on:
if self.current_transcription_update:
self.message_queues['TranscriptionUpdate'].put(self.current_transcription_update)
self.curr_message['TranscriptionUpdate'] = self.current_transcription_update
self.current_transcription_update = ""
if self.current_transcription_stabilized:
self.message_queues['TranscriptionStabilized'].put(self.current_transcription_stabilized)
self.curr_message['TranscriptionStabilized'] = self.current_transcription_stabilized
self.current_transcription_stabilized = ""
# Put the recording stopped message into the queue
self.message_queues['RecordingStop'].put(f"Recording stopped: {text}")
self.curr_message['RecordingStop'] = f"{text}"
# If stop callback is set, update it
if self.stop_callback:
self.stop_callback()
def process_sentence(self, *args, **kwargs):
text = args[0] if args else ""
self.message_queues['ProcessedText'].put(f"Processed text: {text}")
self.curr_message['ProcessedText']=f"{text}"
if self.processed_text_callback:
self.processed_text_callback(text)
def _turn_on_loop(self):
while True:
if self.is_turned_on:
self.recorder.text(self.process_sentence)
time.sleep(0.1) # Use time.sleep instead of asyncio.sleep
def turn_on(self):
self.is_turned_on = True
return self # Return the instance to allow method chaining
def turn_off(self):
self.is_turned_on = False
return self # Return the instance to allow method chaining
def force_turn_off(self):
self.is_turn_on = False
self.recorder.stop()
return self
def set_start_callback(self, callback):
self.start_callback = callback
return self # Return the instance to allow method chaining
def set_stop_callback(self, callback):
self.stop_callback = callback
return self # Return the instance to allow method chaining
def set_transcription_update_callback(self, callback):
self.transcription_update_callback = callback
return self # Return the instance to allow method chaining
def set_transcription_stabilized_callback(self, callback):
self.transcription_stabilized_callback = callback
return self # Return the instance to allow method chaining
def set_processed_text_callback(self, callback):
self.processed_text_callback = callback
return self # Return the instance to allow method chaining
def get_messages(self, message_type):
if message_type in self.message_queues:
messages = list(self.message_queues[message_type].queue)
self.message_queues[message_type].queue.clear()
return messages
else:
return []
"""
import socket
from PIL import Image, ImageTk
class LoadingAnimation:
def __init__(self, parent, filename, width=150, height=150):
self.parent = parent
self.is_running = False
self.width = width
self.height = height
# Load the frames of the GIF animation and resize them
self.frames = self.load_gif_frames(filename, self.width, self.height)
# Get the background color of the parent window
self.bg_color = parent.cget('bg')
# Create a canvas widget to draw the animation with the same background color as the window
self.canvas = tk.Canvas(self.parent, width=self.width, height=self.height, bg=self.bg_color, highlightthickness=0)
self.canvas.pack()
# Display the first frame of the animation
self.current_frame = 0
self.image_item = None
self.update_image()
def load_gif_frames(self, filename, width, height):
gif = Image.open(filename)
frames = []
for frame in range(0, gif.n_frames):
gif.seek(frame)
# Resize each frame to the desired width and height
resized_frame = gif.resize((width, height), Image.ANTIALIAS)
frames.append(ImageTk.PhotoImage(resized_frame))
return frames
def update_image(self):
# Get the size of the current frame
frame_width = self.width
frame_height = self.height
# Calculate the center of the canvas
center_x = self.width / 2
center_y = self.height / 2
# Calculate the position of the image on the canvas
x0 = center_x - frame_width / 2
y0 = center_y - frame_height / 2
# If image item already exists, delete it
if self.image_item:
self.canvas.delete(self.image_item)
# Display the current frame centered on the canvas
self.image_item = self.canvas.create_image(x0, y0, image=self.frames[self.current_frame], anchor="nw")
def update_frame(self):
if self.is_running:
self.current_frame = (self.current_frame + 1) % len(self.frames)
self.update_image()
self.parent.after(50, self.update_frame)
def start_animation(self):
self.is_running = True
self.update_frame()
def stop_animation(self):
self.is_running = False
import markdown
class HTMLGenerator:
def __init__(self):
self.themes = {
"default": ("red", "green", "blue", "purple"),
"light": ("#333333", "#007ACC", "#009688", "#FF5722"),
"dark": ("#FFFFFF", "#FFD600", "#FF4081", "#4CAF50"),
"monochrome": ("#212121", "#795548", "#607D8B", "#FF5722"),
"nature": ("#263238", "#43A047", "#EF6C00", "#009688"),
"ocean": ("#37474F", "#FFD600", "#0288D1", "#FFA000"),
"sunset": ("#263238", "#FF7043", "#EF5350", "#FFC107"),
"forest": ("#37474F", "#4CAF50", "#689F38", "#795548"),
"autumn": ("#3E2723", "#FF6F00", "#8D6E63", "#FFAB91"),
"pastel": ("#424242", "#7986CB", "#AED581", "#FF8A65"),
"space": ("#FFFFFF", "#FFD600", "#B39DDB", "#4CAF50"),
"desert": ("#5D4037", "#FF8F00", "#FFA000", "#4E342E"),
"spring": ("#37474F", "#43A047", "#4CAF50", "#FFC107"),
"rainbow": ("#000000", "#FF0000", "#FF7F00", "#FFFF00"),
"vintage": ("#3E2723", "#795548", "#8D6E63", "#FFAB91"),
"winter": ("#263238", "#039BE5", "#03A9F4", "#4CAF50")
}
self.sub_section_colors = {
"default": ["#f2f2f2", "#e6e6e6"],
"light": ["#f0f8ff", "#e0f7fa"],
"dark": ["#ffe0b2", "#ffcc80"],
"monochrome": ["#f5f5f5", "#e0e0e0"],
"nature": ["#c8e6c9", "#a5d6a7"],
"ocean": ["#e1f5fe", "#b3e5fc"],
"sunset": ["#ffccbc", "#ffab91"],
"forest": ["#dcedc8", "#c5e1a5"],
"autumn": ["#ffecb3", "#ffe082"],
"pastel": ["#f8bbd0", "#f48fb1"],
"space": ["#b2ebf2", "#80deea"],
"desert": ["#ffecb3", "#ffe082"],
"spring": ["#c8e6c9", "#a5d6a7"],
"rainbow": ["#f5f5f5", "#e0e0e0"],
"vintage": ["#ffe0b2", "#ffcc80"],
"winter": ["#e1f5fe", "#b3e5fc"]
}
def inline_css(self, html_content):
soup = BeautifulSoup(html_content, 'html.parser')
style_tag = soup.find('style')
if style_tag:
try:
css_styles = cssutils.parseString(style_tag.string)
except cssutils.CSSParseException as e:
print(f"Error parsing CSS: {e}")
return html_content
style_tag.decompose()
for rule in css_styles:
if rule.type == rule.STYLE_RULE:
css_text = rule.style.getCssText()
for selector in rule.selectorList:
elements = soup.select(selector.selectorText)
for element in elements:
existing_styles = element.get('style', '')
if existing_styles:
element['style'] = f"{existing_styles}; {css_text}"
else:
element['style'] = css_text
return str(soup)
def generate_html_response(self,prompt, response_title, colors, section_colors, html_content, theme="default", use_backgrounding=True):
color1, color2, color3, color4 = colors
soup = BeautifulSoup(html_content, 'html.parser')
# Extract headings, paragraphs, ordered and unordered lists, and strong tags
sections = soup.find_all(['h3', 'h4', 'p', 'ol', 'ul', 'li', 'strong'])
content_html = ""
#in_section = False # Flag to track whether we are currently inside a section
for section_index, section in enumerate(sections):
section_color = section_colors[section_index % len(section_colors)]
if section.name == 'h3':
content_html += f'<div class="sub-section" style="background-color: {section_color};">\n<h2>{section.text}</h2>\n'
#in_section = True
elif section.name == 'h4':
content_html += f'<div class="sub-section" style="background-color: {section_color};">\n<h3>{section.text}</h3>\n'
#in_section = True
elif section.name == 'p':
if section.parent.name=='li':
pass
elif section.find('strong'):
pass
else:
#if not in_section:
content_html += f'<div class="sub-section" style="background-color: {section_color};">\n'
# in_section = True
content_html += f'<p>{section.text}</p>\n'
elif section.name in ['ol', 'ul']:
#if not in_section:
content_html += f'<div class="sub-section" style="background-color: {section_color};">\n'
# in_section = True
content_html += f'<{section.name}>\n'
elif section.name == 'li':
# Check if the li contains a strong tag
strong_tag = section.find('strong')
if strong_tag:
pass
#skip
# If yes, include the strong tag content in the list item
#content_html += f'<li><strong>{strong_tag.text}</strong>{section.text.replace(strong_tag.text, "")}</li>\n'
else:
content_html += f'<li>{section.text}</li>\n'
elif section.name == 'strong':
# Treat strong tag as heading
if section.parent.name == 'p':
content_html += f'<h3>{section.text}</h3>'
strong_text = section.text
# If strong tag is inside a list item, add the remaining text in the list item as a paragraph
strong_text = section.text
li_content = section.parent.text.replace(strong_text, '', 1).strip()
content_html += f'<p>{li_content}</p>\n'
else:
# Treat it as a standalone section
content_html += f'<div class="sub-section" style="background-color: {section_color};">\n<h3>{section.text}</h3>\n'
if section.parent.name == 'li':
# If strong tag is inside a list item, add the remaining text in the list item as a paragraph
strong_text = section.text
li_content = section.parent.text.replace(strong_text, '', 1).strip()
content_html += f'<p>{li_content}</p>\n'
body_bg_color = "#f8f8f8" if use_backgrounding else "transparent"
html_template = f'<!DOCTYPE html> \
<html lang="en"> \
<head> \
<meta charset="UTF-8"> \
<meta name="viewport" content="width=device-width,initial-scale=1.0"> \
<title>{response_title}</title> \
<style> \
body {{ \
font-family: Arial, sans-serif; \
background-color: {body_bg_color}; \
margin: 0; \
padding: 10px; \
}} \
h1 {{ \
color: {color1}; \
font-size: 20px; \
margin-bottom: 8px; \
}} \
h2 {{ \
color: {color2}; \
font-size: 18px; \
margin-bottom: 6px; \
}} \
h3 {{ \
color: {color3}; \
font-size: 16px; \
margin-bottom: 4px; \
}} \
h4 {{ \
color: {color4}; \
font-size: 14px; \
margin-bottom: 4px; \
}} \
p {{ \
line-height: 1.4; \
margin-bottom: 8px; \
}} \
section {{ \
background-color: #ffffff; \
border-radius: 5px; \
margin-bottom: 10px; \
padding: 15px; \
}} \
.sub-section {{ \
border-radius: 5px; \
padding: 10px; \
margin-bottom: 8px; \
}} \
</style> \
</head> \
<body> \
<section> \
<p>{prompt}</p> \
<div class="sub-section"> \
</div> \
</section> \
<section> \
{content_html} \
</section> \
</body> \
</html>'
return self.inline_css(html_template)
def respond_with_html(self, prompt, contents, theme="default", use_backgrounding=True):
response_title = "Response Title"
if theme not in self.themes:
theme = "default"
theme_colors = self.themes[theme]
section_colors = self.sub_section_colors[theme]
html_response = self.generate_html_response(prompt, response_title, theme_colors, section_colors, contents)
return html_response
def display_html(self, html_content):
root = tk.Tk()
root.title("HTML Content")
html_label = HTMLLabel(root, html=html_content)
html_label.pack(fill="both", expand=True)
root.mainloop()
def generate_and_display_html(self, prompt, contents, theme="default", use_backgrounding=True):
html_response = self.respond_with_html(prompt, markdown.markdown(contents), theme, use_backgrounding)
#self.display_html(html_response)
return html_response
import io
from tkinter import filedialog
import threading
from tkinter.scrolledtext import ScrolledText
from tkinter.scrolledtext import ScrolledText
class ScrolledCanvas(tk.Frame):
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs)
self.canvas = tk.Canvas(self, **kwargs)
self.v_scroll = tk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
self.h_scroll = tk.Scrollbar(self, orient="horizontal", command=self.canvas.xview)
self.canvas.config(yscrollcommand=self.v_scroll.set, xscrollcommand=self.h_scroll.set)
self.canvas.grid(row=0, column=0, sticky="nsew")
self.v_scroll.grid(row=0, column=1, sticky="ns")
self.h_scroll.grid(row=1, column=0, sticky="ew")
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
class PDFViewerApp:
def __init__(self, parent=None, **kwargs):
self.parent = parent
self.pdf_file = None
self.pdf_document = None
self.current_page = 0
self.total_pages = 0
self.image1 = None
self.thread_lock = threading.Lock()
self.is_packed = False
self.setup_ui()
def parse_and_extract_number(self, code_key):
# Regular expression to find numeric values
pattern = r'\d+'
# Search for numeric values in the code_key
matches = re.findall(pattern, code_key)
# Extract the first numeric value found (if any)
if matches:
return int(matches[0])
else:
return None
def setup_ui(self):
self.frame = tk.Frame(self.parent)
# Create a ScrolledCanvas widget for displaying the page
self.scrolled_canvas = ScrolledCanvas(self.frame)
self.scrolled_canvas.pack(fill=tk.BOTH, expand=True)
# Create a canvas widget inside the ScrolledCanvas
self.canvas = self.scrolled_canvas.canvas
# Bind the resize event of the canvas widget
self.canvas.bind("<Configure>", self.resize_canvas)
def pack(self, **kwargs):
self.frame.pack(**kwargs)
self.is_packed = True
def pack_forget(self):
self.frame.pack_forget()
self.is_packed = False
def set_pdf(self, pdf_file_path):
self.pdf_file = pdf_file_path
self.pdf_document = fitz.open(self.pdf_file)
self.total_pages = len(self.pdf_document)
threading.Thread(target=self.show_page, args=(self.current_page,)).start()
def show_page(self, page_number):
with self.thread_lock:
self.current_page = page_number
if self.pdf_document:
page = self.pdf_document.load_page(page_number)
pix = page.get_pixmap()
img_data = pix.tobytes("ppm")
img = Image.open(io.BytesIO(img_data))
# Get the canvas dimensions
canvas_width = self.canvas.winfo_width()
canvas_height = self.canvas.winfo_height()
# Resize the image with Lanczos filter for better text quality
img = img.resize((canvas_width, canvas_height), Image.LANCZOS)
photo = ImageTk.PhotoImage(image=img)
# Update the canvas image
self.canvas.create_image(0, 0, image=photo, anchor='nw')
# Keep reference to prevent garbage collection
self.image1 = photo
def show_prev_page(self):
if self.current_page > 0:
self.current_page -= 1
threading.Thread(target=self.show_page, args=(self.current_page,)).start()
def show_next_page(self):
if self.current_page < self.total_pages - 1:
self.current_page += 1
threading.Thread(target=self.show_page, args=(self.current_page,)).start()
def resize_canvas(self, event):
# Update the canvas to display the current page
threading.Thread(target=self.show_page, args=(self.current_page,)).start()
import base64
import pygame
import requests
from io import BytesIO
import tkinter as tk
from tkinter import ttk
import tkinter as tk
import os
import pickle
import hashlib
import tkinter as tk
import os
import pickle
import hashlib
class DraggableWidget:
instances = {} # Dictionary to store instances keyed by unique identifier
def __init__(self, widget, master=None, grid_size=15, **kwargs):
# Remove the 'key' command from kwargs if it exists
kwargs.pop('command', None)
self.master = master
self.dragging = False
self.widget = widget
self.grid_size = grid_size
self.widget_name = self.encode_widget_name(widget, **kwargs) # Encoded widget name
self.widget_name2 = kwargs.get('text', None)
print(kwargs)
self.widget.bind("<ButtonPress-1>", self.on_drag_start)
self.widget.bind("<ButtonRelease-1>", self.on_drag_stop)
self.widget.bind("<B1-Motion>", self.on_drag_motion)
self.master.bind("<Configure>", DraggableWidget.on_window_configure) # Bind to window resize event
# Initialize initial_width and initial_height if not initialized yet
DraggableWidget.initial_width = getattr(DraggableWidget, 'initial_width', self.master.winfo_width())
DraggableWidget.initial_height = getattr(DraggableWidget, 'initial_height', self.master.winfo_height())
DraggableWidget.g_master=self.master
# Add the instance to the dictionary using the widget name as the key
DraggableWidget.add_instance(self.widget_name, self)
self.master.after(1000, self.load_position) # Load the position from storage after a delay
@staticmethod
def on_window_configure(event):
# Get the top-level window associated with the event
top_level_window = DraggableWidget.g_master
# Get the width and height of the top-level window
width = top_level_window.winfo_width()
height = top_level_window.winfo_height()
# Check if the configure event is a window resize event
if (width != DraggableWidget.initial_width or height != DraggableWidget.initial_height):
# Update initial width and height
DraggableWidget.initial_width = width
DraggableWidget.initial_height = height
# Call global_load_position to handle window resize
DraggableWidget.global_load_position()
@staticmethod
def global_load_position(event=None):
# Call load_position method for each instance
for instance in DraggableWidget.instances.values():
instance.load_position()
@staticmethod
def get_instance(widget_name):
# Retrieve instance from dictionary by widget name
return DraggableWidget.instances.get(widget_name)
@staticmethod
def add_instance(widget_name, instance):
# Add instance to the dictionary using the widget name as the key
DraggableWidget.instances[widget_name] = instance
def on_drag_start(self, event):
self.start_x = event.x
self.start_y = event.y
self.dragging = True
def on_drag_stop(self, event):
self.dragging = False
self.save_position() # Save the position to storage
def on_drag_motion(self, event):
if self.dragging:
# Calculate new coordinates
x = self.widget.winfo_x() - self.start_x + event.x
y = self.widget.winfo_y() - self.start_y + event.y
# Lock to grid
x = self.snap_to_grid(x)
y = self.snap_to_grid(y)
# Update widget position
self.widget.place_configure(x=x, y=y)
def snap_to_grid(self, coordinate):
# Snap the coordinate to the nearest multiple of grid_size
return int(round(coordinate / self.grid_size)) * self.grid_size
def encode_widget_name(self, widget, **kwargs):
# Combine widget name and arguments into a string
widget_info = f"{type(widget).__name__}_{sorted(kwargs.items())}"
# Encode the widget info using SHA-256 hash
hashed_widget_info = hashlib.sha256(widget_info.encode()).hexdigest()
return hashed_widget_info
def load_position(self,event=None):
position_file = os.path.join("Widget_Position", f"{self.widget_name}_position.pkl")
try:
with open(position_file, "rb") as f:
print("Found_Something",self.widget_name2)
position = pickle.load(f)
# Load position as fraction of window dimensions
x = self.master.winfo_width() * position[0]
y = self.master.winfo_height() * position[1]
self.widget.place_configure(x=x, y=y)
except FileNotFoundError:
pass
def save_position(self):
position = (self.widget.winfo_x() / self.master.winfo_width(), self.widget.winfo_y() / self.master.winfo_height())
print("Saving")
# Save position as fraction of window dimensions
position_file = os.path.join("Widget_Position", f"{self.widget_name}_position.pkl")
os.makedirs("Widget_Position", exist_ok=True) # Create the folder if it doesn't exist
with open(position_file, "wb") as f:
pickle.dump(position, f)
def pack(self, *args, **kwargs):
# Extract and remove 'alter' from kwargs if it exists
alter = kwargs.pop('alter', False)
# Checking if alter is True
if alter:
# If alter is True, call self.widget.pack() with the provided arguments and keyword arguments
self.widget.pack(*args, **kwargs)
else:
# If alter is not True, simply call self.widget.pack() without any arguments
self.widget.pack()
# Call self.load_position after a delay of 200 milliseconds
self.master.after(200, self.load_position)
def pack_forget(self):
self.widget.pack_forget()
# Handle undefined attribute calls by delegating to the underlying widget
def __getattr__(self, attr):
return getattr(self.widget, attr)
def create_draggable_label(master=None, **kwargs):
label = LabelCustom(master, **kwargs)
return DraggableWidget(label, master, **kwargs)
def create_draggable_entry(master=None, **kwargs):
entry = EntryCustom(master, **kwargs)
return DraggableWidget(entry, master, **kwargs)
def create_draggable_text(master=None, **kwargs):
pass
# text = TextCustom(master, **kwargs)
# return DraggableWidget(text, master, **kwargs)
def create_draggable_checkbutton(master=None, **kwargs):
checkbutton = CheckbuttonCustom(master, **kwargs)
return DraggableWidget(checkbutton, master, **kwargs)
def create_draggable_button(master=None, **kwargs):
button = ButtonCustom(master, **kwargs)
return DraggableWidget(button, master, **kwargs)
def create_draggable_panedwindow(master=None, **kwargs):
paned_window = PanedWindowCustom(master, **kwargs)
return DraggableWidget(paned_window, master, **kwargs)
def create_draggable_optionsmenu(master=None, **kwargs):
options_menu = None#OptionsMenuCustom(master, **kwargs)
return DraggableWidget(options_menu, master, **kwargs)
# Custom widget classes
LabelCustom = tk.Label
EntryCustom = tk.Entry
# TextCustom = tk.Text # Uncomment if needed
CheckbuttonCustom = tk.Checkbutton
ButtonCustom = tk.Button
PanedWindowCustom = tk.PanedWindow
# Assign custom classes to tkinter widget classes
tk.Label = create_draggable_label
tk.Entry = create_draggable_entry
# tk.Text = create_draggable_text # Uncomment if needed
tk.Checkbutton = create_draggable_checkbutton
tk.Button = create_draggable_button
tk.PanedWindow = create_draggable_panedwindow
class JsonViewerApp:
def __init__(self, text_font=("Trebuchet MS", 12), l_spacing1=10, l_spacing3=10):
global model
self.generator = HTMLGenerator()
self.model=model
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.is_single_instance = self.check_single_instance()
print("Everyone Gets Here")
if not self.is_single_instance:
print("Another instance is already running. Exiting.")
return
print("Only ONe Person Reaches Here")
self.root = tk.Tk()
self.root.title("Jarvis Analysis Viewer")
print(ChatGPT.GPT3ChatBot.chat(user_input="",
user_system_message='FAVOUR LONG RESPONSES broken into headings and subheading'
# Except when the text starts with Jarvis, then respond in a conversational, like informative manner"
,use_user_system_message=True))
# Extract the first element of each tuple
first_elements = [value for value in self.generator.themes.keys()]