-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcs.py
More file actions
758 lines (636 loc) · 24.6 KB
/
cs.py
File metadata and controls
758 lines (636 loc) · 24.6 KB
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
'''
cs.py CodeScriber Code Editor
Hak-able Desktop Code Editor
Oct 2024 Michael Leidel
https://github.com/MLeidel/CodeScriber
Dec 2025 Fixing "New" to require file name
Feb 2026 Alt-u opens selected URL
'''
import sys
import os
import glob
import time
import subprocess
import webbrowser
import platform
import shutil
from pathlib import Path
from tkinter.ttk import *
from tkinter import filedialog
from tkinter import messagebox
from datetime import datetime
from ttkthemes import ThemedTk
from openai import OpenAI
from spellchecker import SpellChecker
from screeninfo import get_monitors
import webview
import markdown
import iniproc
version = "CodeScriber 2.5.2"
p = os.path.realpath(__file__)
p = os.path.dirname(p) + "/"
optionsFileName = p+"options.ini"
lastFileName = p+"lastfile"
tags = p+"tags.js"
wingeo = p+"wingeo"
spell = SpellChecker()
rec = [] # recent file list GLOBAL
srec = "" # csv string for javascript recent file list
opts = [] # storeing options from the options.ini file
opts = iniproc.read(optionsFileName,'ailog',
'backup',
'terminal',
'filemanager',
'previous',
'browser', # 5
'scope',
'run1',
'run2',
'run3',
'run4', # 10
'nam1',
'nam2',
'nam3',
'nam4',
'theme', # 15
'openai',
'model',
'role',
'aiconfirm') # 19
current_file = "" # tracks current file in use
current_path = opts[6] # tracks path
myfpath = os.path.abspath(__file__) # save this instance full path
myOS = platform.system() # Linux or Windows
mypy = 'python3' # for linux default
messages = [] # list to hold AI conversation
# UNCOMMENT THIS FUNCTION TO WORK ON DUAL MONITORS (there is more)
def window_coord():
''' use this func when using multiple monitors '''
px = window.x
py = window.y
geo = f"0x0+{px}+{py}" # keep tkinter on left screen
return geo
def find_file(filename, search_path):
''' finds full-path of a file on Linux system '''
for root, dirs, files in os.walk(search_path):
if filename in files:
return os.path.join(root, filename)
return None
def mdToHTML():
''' convert MD file to HTML file '''
with open(current_file, 'r', encoding='utf-8') as file:
htmlText = markdown.markdown(file.read(), extensions=['extra'])
htmlFile = current_file[:-3] + ".html"
# open in default browser
with open(htmlFile, 'w', encoding='utf-8') as file:
file.write(htmlText)
#
# Recent File Functions
#
def loadRecent():
''' open and read in the 'recent' text file containing recent file list '''
global rec
with open('recent', 'r', encoding='utf-8') as file:
rec = file.readlines()
rec = [item.rstrip('\n') for item in rec]
def saveRecent():
''' save the recent file list to 'recent' text file '''
global srec
n = len(rec)
c = 0
with open("recent", "w", encoding='utf-8') as file:
srec = ""
for item in rec:
file.write(item + "\n")
# also re-build csv string for javascript
srec += item
c += 1
if c < n:
srec += ","
def newRecent(item):
''' modify the recent file list '''
global rec
c = rec.count(item) # is item in the current list
if c > 0:
x = rec.index(item) # get the index of the item
if x > 0:
rec.remove(item) # move the item up to the top of list
rec.insert(0, item)
else:
pass # already at top of list
else:
n = len(rec) # put new item into to list
if n > 8: # keep the list to 9 or less items (COULD BE A VARIABLE)
rec.pop(n-1) # remove the bottom item (0 relative)
rec.insert(0, item) # put the new item at the top
def updateRecents(item):
''' update the recent file with next item ( open file )
Every 'open file' performs this function '''
if os.path.isfile("recent") is False:
with open("recent", "w", encoding='utf-8') as fout:
fout.write("options.ini\n")
loadRecent() # read in the recent file list
if item != "":
newRecent(item) # put item at the top of list
saveRecent() # write back the recent file list
# def select_files():
# ''' Prompt to open a file using desktop openFileDialog '''
# if MONITORS > 1:
# root = ThemedTk(theme="black") # provides a theme for dialogs
# root.geometry(window_coord()) # on current monitor
# file_paths = filedialog.askopenfilenames(initialdir=current_path,
# # initialfile=os.path.basename(current_file),
# title="Open files",
# filetypes=(("all files", "*.*"),
# ("Python", "*.py *.pyw"),
# ("C/C++", "*.c *.cpp"),
# ("h", "*.h"),
# ("Javascript", "*.js"),
# ("HTML", "*.html"),
# ("CSS", "*.css")))
# if MONITORS > 1:
# root.destroy() # no longer needed
# if file_paths:
# return list(file_paths) # Return as a list of file paths
# return []
def select_files():
''' Prompt to open a file using desktop openFileDialog '''
if MONITORS > 1:
root = ThemedTk(theme="black") # provides a theme for dialogs
root.geometry(window_coord()) # on current monitor
filetypes = (
'All files (*.*)',
'Python Files (*.py;*.pyw)',
'C Files (*.c;*.cpp)',
'Header Files (*.h)',
'JavaScript Files (*.js)',
'HTML Files (*.html)',
'CSS Files (*.css)'
)
print(os.path.basename(current_file))
result = window.create_file_dialog(
webview.FileDialog.OPEN, allow_multiple=True,
directory=current_path,
file_types=filetypes
)
if MONITORS > 1:
root.destroy() # no longer needed
if result:
return list(result) # Return as a list of file paths
return []
def runOptions(inx):
''' User executes external process (run1 - run4)
checks for web page or system process '''
item = opts[inx]
if item.startswith("http"):
webbrowser.open(item)
else:
# check for fullpath or path {f} or {p}
run = item.replace("{f}", current_file)
run = run.replace("{p}", current_path)
os.system(run)
def windows_path(path):
''' reverse / for Windows path '''
ws = "\\"
rp = path.replace("/", ws)
return rp
def trim_trailing_spaces(code):
''' Trim Trailing space from lines of code '''
lines = code.splitlines()
trimmed_lines = [line.rstrip() for line in lines]
trimmed_code = '\n'.join(trimmed_lines)
return trimmed_code + '\n'
def save_backup_file():
''' Check if the file exists '''
if not os.path.isfile(current_file):
return
# Extract the directory and the base file name
dir_name, base_name = os.path.split(current_file)
# Get the current date and time
current_time = datetime.now()
# Format the current time as a string
timestamp_str = current_time.strftime("%Y%m%d_%H") # %M%S
# Construct the backup file name
backup_file_name = f"bkup_{base_name}_{timestamp_str}"
backup_file_path = os.path.join(dir_name, backup_file_name)
# Copy the original file to the backup file
shutil.copy2(current_file, backup_file_path)
def gptCode(key: str, model: str, query: str) -> str:
''' Method to access OpenAI API
Control comes here from gptAccess(...)
Conversation is not serialized. '''
global messages
# print(opts[18])
try:
client = OpenAI(
api_key = os.environ.get(key) # openai API
)
except Exception as e:
return e
# add the new query to the messages
messages.append(
{"role": "user", "content": query}
)
try:
response = client.chat.completions.create(
model=model,
messages=messages
)
output = response.choices[0].message.content
# append response to messages
messages.append(
{"role": "assistant", "content": output}
)
return output
except Exception as e:
return e
#
# P Y W E B V I E W
#
# Javascript pywebview API functions connect to JAVASCRIPT
#
#
class Api:
''' All of these are called from Javascript '''
def onClose(self):
''' immediate close no ask '''
# save last opened filename
with open(lastFileName, "w", encoding='utf-8') as fout:
fout.write(current_file)
# save last window dimensions
with open(wingeo, "w", encoding='utf-8')as fout:
fout.write(str(int(window.x)) + "|"
+ str(int(window.y)) + "|"
+ str(int(window.width)) + "|"
+ str(int(window.height)))
# exit app
window.destroy()
sys.exit()
def set_current_file(self, content):
''' In a tab switch the current_file is updated '''
global current_file, current_path
current_file = content
current_path = os.path.dirname(current_file)
def getFileName(self):
''' JS/HTML needs the current filename '''
return current_file
def open_file(self):
''' Prompt to open a file using desktop openFileDialog '''
global current_file, current_path
selected = select_files()
# print(selected)
if len(selected) == 0:
return ''
for file in selected:
# print(file)
current_file = file
current_path = os.path.dirname(current_file)
updateRecents(current_file) # update recent files list/file
if opts[1] == "yes":
save_backup_file() # save backup on open file
window.evaluate_js("openCmdFile()")
time.sleep(.3)
# def save_file(self, content):
# ''' Save-A or Ctrl-Shift-S
# builds HTML from an ".md" file save
# '''
# global current_file, current_path
# if MONITORS > 1:
# root = ThemedTk(theme="black") # provides a theme for dialogs
# root.geometry(window_coord()) # on current monitor
# file_path = filedialog.asksaveasfilename(initialdir=current_path,
# defaultextension=".txt",
# initialfile=os.path.basename(current_file),
# filetypes=(("all files", "*.*"),
# ("Python", "*.py *.pyw"),
# ("C/C++", "*.c *.cpp"),
# ("h", "*.h"),
# ("Javascript", "*.js"),
# ("HTML", "*.html"),
# ("CSS", "*.css")))
# if MONITORS > 1:
# root.destroy() # no longer needed
# if file_path:
# current_file = file_path
# current_path = os.path.dirname(file_path)
# else:
# return ''
# if not current_file.endswith(".md"):
# content = trim_trailing_spaces(content)
# with open(current_file, 'w', encoding='utf-8') as file:
# file.write(content)
# if current_file.endswith(".md"):
# mdToHTML()
# # save last file name
# # with open(lastFileName, "w", encoding='utf-8') as fout:
# # fout.write(current_file)
# return current_file
def save_file(self, content):
''' Save-A or Ctrl-Shift-S
builds HTML from an ".md" file save
'''
global current_file, current_path
if MONITORS > 1:
root = ThemedTk(theme="black") # provides a theme for dialogs
root.geometry(window_coord()) # on current monitor
filetypes = (
'All files (*.*)',
'Python Files (*.py;*.pyw)',
'C Files (*.c;*.cpp)',
'Header Files (*.h)',
'JavaScript Files (*.js)',
'HTML Files (*.html)',
'CSS Files (*.css)'
)
file_path = window.create_file_dialog(
webview.FileDialog.SAVE, directory=current_path,
file_types=filetypes
)
if MONITORS > 1:
root.destroy() # no longer needed
if file_path:
current_file = file_path[0]
selected_path = file_path[0]
current_path = os.path.dirname(selected_path)
else:
return ''
if not current_file.endswith(".md"):
content = trim_trailing_spaces(content)
with open(current_file, 'w', encoding='utf-8') as file:
file.write(content)
if current_file.endswith(".md"):
mdToHTML()
# save last file name
# with open(lastFileName, "w", encoding='utf-8') as fout:
# fout.write(current_file)
return current_file
def quick_save_file(self, content):
''' Save or Ctrl-S
builds HTML from an ".md" file save
'''
currbase = os.path.basename(current_file)
# if not os.path.isfile(current_file) and not os.path.isfile(currbase):
# self.save_file(content)
# return
if not current_file.endswith(".md"):
content = trim_trailing_spaces(content)
with open(current_file, 'w', encoding='utf-8') as file:
file.write(content)
if current_file.endswith(".md"):
mdToHTML()
# save last file name
# with open(lastFileName, "w", encoding='utf-8') as fout:
# fout.write(current_file)
return current_file
def check_new_to_overwrite(self, content):
''' HTML check to see if "new" file exists '''
currbase = os.path.basename(content)
if os.path.isfile(content) or os.path.isfile(currbase):
# print("YES", content)
return "yes"
else:
# print(content)
return content
def open_URL(self, content):
webbrowser.open(content)
def getCmdFile(self):
''' Get the starting file from command line
File was switched into the current_file/path fields
If no command line file then opens lastfile '''
if os.path.isfile(current_file):
updateRecents(current_file)
with open(current_file, 'r', encoding='utf-8') as file:
return file.read()
return '' # File Not Found or no previous on startup
def gptAccess(self, content) -> str:
''' User has hit Ctrl-G with either an AI prompt or the word "log".
Access OpenAI and return query response
or, return ailog.md if "log" was requested
Also write response to the log if option is turned on. '''
global messages
if content.lower().strip() == "log":
with open("ailog.md", 'r', encoding='utf-8') as fin:
return fin.read()
if content.lower().strip() == "new":
messages = [] # clear message chain for new conversation
return "NEW CHAT"
if content.lower().strip() == "prompt":
with open("prompt.md", 'r', encoding='utf-8') as fin:
return fin.read()
key = opts[16] # openai User Key
mod = opts[17] # model to use
res = gptCode(key, mod, content)
if opts[0].lower() == "yes":
timestamp_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open("ailog.md", "a", encoding='utf-8') as fout:
fout.write(timestamp_str + "\n\n")
fout.write(content + "\n---\n")
fout.write(res + "\n\n---\n\n")
with open("ailog.md", 'r', encoding='utf-8') as file:
htmlText = markdown.markdown(file.read(), extensions=['extra'])
with open("ailog.html", 'w', encoding='utf-8') as file:
file.write(htmlText)
return res
def execMarkdown(self):
''' open the markdown's HTML file in specified browser '''
if not current_file.endswith(".md"):
return
# change to .html file
htmlFile = current_file[:-3] + ".html"
file_path = Path(htmlFile).resolve()
file_url = file_path.as_uri()
print(file_url)
# open in default browser
if opts[5].lower() == "default":
webbrowser.open(file_url)
else:
subprocess.call([opts[5], file_url])
def execWebbrowser(self):
''' open the web browser specified in the options.ini '''
if opts[5].lower() == "default":
webbrowser.open(current_file)
else:
subprocess.call([opts[5], current_file])
def execFileMgr(self):
''' open the file manager specified in the options.ini '''
#os.system(opts[3] + " " + current_path)
if myOS == "Windows":
wp = windows_path(current_path)
subprocess.call([opts[3], wp])
else:
fm = opts[3].split()
fm.append(current_path)
# subprocess.call([opts[3], current_path])
subprocess.call(fm)
def execTerminal(self):
''' open the terminal specified in the options.ini
This logic is to accommodate Windows Terminal:
wt -d
and Linux FMs like gnome-terminal:
gnome-terminal --working-directory=
Windows requires the extra space before the directory path
'''
if myOS == 'Windows':
os.system(opts[2] + " " + current_path)
else:
os.system(opts[2] + current_path)
def delete_backups(self):
''' Removes backup files for current directory '''
if MONITORS > 1:
root = ThemedTk(theme="black") # provides a theme for dialogs
root.geometry(window_coord()) # on current monitor
# rsp = messagebox.askokcancel("Remove Backups?", f" for: {current_path}")
rsp = window.create_confirmation_dialog('Confirm','Do you want to proceed?')
if rsp is True:
files = glob.glob(current_path + "/bkup_*")
for file_path in files:
os.remove(file_path)
if MONITORS > 1:
root.destroy()
def exec1(self):
''' execute/open run 1 opts[7] '''
runOptions(7)
def exec2(self):
''' open run 2 '''
runOptions(8)
def exec3(self):
''' open run 3 '''
runOptions(9)
def exec4(self):
''' open run 4 '''
runOptions(10)
def getRunNames(self):
''' title names for run1-4 tools menu items -
send names 1-4 from options.ini 11 12 13 14 '''
names = ",".join(opts[11:15])
return names
def openSelected(self, filename):
''' open the requested recent file
it's possible file was removed on
disk so we return 'file not found'
When no path for file assume program
directory "p" '''
global current_file, current_path
current_file = filename
current_path = os.path.dirname(current_file)
if current_path == "":
current_path = p
current_file = current_path + current_file
if current_file:
try:
with open(current_file, 'r', encoding='utf-8') as file:
txt = file.read()
except:
return "file not found"
updateRecents(current_file)
if opts[1] == "yes":
save_backup_file()
return txt
return ''
def returnRecents(self):
''' requesting recent file list as csv string '''
return srec
def open_spellcheck(self, content):
''' process sting of words and return results '''
wlist = content.split() # string to list
words = spell.unknown(wlist) # spell check the list
strwords = "<br>"
for word in words: # concat spell output into one string
strwords += word + "<br>"
# Get the one `most likely` answer
# spell.correction(word)
# Get a list of `likely` options
strwords += str(spell.candidates(word))
strwords += "<hr>"
return strwords
def on_file_drop(self, filename):
''' Search for the specified filename in the given directory
and its subdirectories. Return a csv string of fullpaths. '''
print(filename)
search_path = opts[6] # file system scope. ex: /home/usER...
matches = []
drpath = "" # holds csv string
c = 0 # for counting "," in the csv string
for root, dirs, files in os.walk(search_path):
if filename in files:
matches.append(os.path.join(root, filename))
# create csv string from matches list
n = len(matches)
for item in matches:
drpath += item
c += 1
if c < n:
drpath += ","
print(drpath)
return drpath
def reLaunch(self):
''' close and re-open this instance '''
python = sys.executable
window.destroy()
os.execl(python, python, *sys.argv)
def addsnipit(self, content):
''' extract trigger word and code to
append a new zen snipit to tags.js
this replaces the fzen.py program '''
sniplist = content.split("\n")
parts = sniplist[1].split(":")
trig = parts[1].strip()
code = sniplist[2:]
# print(trig)
# print(code)
tagstr = "\"" + trig + "\": \""
# escape all double quotes
for line in code:
line = line.replace('"', r'\"')
tagstr += line + "\\n"
tagstr += "\"," # concat final double quote
print("")
print(tagstr)
print("")
# read in the Zen tags file
with open(tags, "r") as fin:
zenlst = fin.readlines()
zenlst = [i.strip() for i in zenlst]
# add the new tag at end of list
zenlst.remove("}; //")
zenlst.append(tagstr)
# write back the list to the file
with open(tags, "w") as fout:
for line in zenlst:
fout.write(line + "\n")
fout.write("}; //\n")
# END OF JS_API CLASS
if __name__ == '__main__':
api = Api()
win = [100,100,800,600] # initialize geo: left,top,width,height
if myOS == 'Windows':
mypy = 'pythonw.exe'
monitors = get_monitors()
MONITORS = len(monitors)
'''
The following opens a file from the command line
or by default the last file used at shut down.
'''
if len(sys.argv) > 1:
current_file = sys.argv[1] # needs a full path !
current_path = os.path.dirname(current_file)
elif os.path.isfile(lastFileName) and opts[4] == "yes":
with open(lastFileName, 'r', encoding='utf-8') as f:
current_file = f.readline().strip()
current_path = os.path.dirname(current_file)
updateRecents(current_file)
if opts[1] == "yes":
save_backup_file()
# get last window size and location
if os.path.isfile(wingeo):
with open(wingeo, 'r', encoding='utf-8') as f:
geom = f.read().strip()
win = geom.split('|') # 0 left, 1 top, 2 width, 3 height
win = [int(i) for i in win] # make integers
urlquery = f"cs.html?theme={opts[15]}&aiconfirm={opts[19]}"
window = webview.create_window(version,
url=urlquery, x=win[0], y=win[1],
width=win[2],
height=win[3],
js_api=api)
webview.start() # (debug=True)