-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
1114 lines (979 loc) · 54.1 KB
/
app.py
File metadata and controls
1114 lines (979 loc) · 54.1 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
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
from __future__ import annotations
from datetime import datetime
from pathlib import Path
from io import BytesIO
from PIL import Image
import streamlit as st
import subprocess
import sysconfig
import requests
import struct
import base64
import shutil
import pydoc
import yaml
import stat
import sys
import re
import os
st.set_page_config(page_title="LabConstrictor",
page_icon="🐍",
layout="wide",
)
MAX_FILE_SIZE_MB = 25
if "ready_for_pr" not in st.session_state:
st.session_state["ready_for_pr"] = False
if "github_repo_url" not in st.session_state:
st.session_state["github_repo_url"] = ""
if "update_upload_queue" not in st.session_state:
st.session_state["update_upload_queue"] = []
if "update_upload_form_key" not in st.session_state:
st.session_state["update_upload_form_key"] = 0
VIEW_WELCOME = "welcome"
VIEW_INITIALIZE = "initialize"
VIEW_UPDATE = "update"
if "active_view" not in st.session_state:
st.session_state["active_view"] = VIEW_WELCOME
st.session_state["stdlib_modules"] = ['__future__', '__hello__', '__phello__', '_abc', '_aix_support', '_android_support',
'_apple_support', '_ast', '_bisect', '_blake2', '_codecs', '_codecs_cn', '_codecs_hk',
'_codecs_iso2022', '_codecs_jp', '_codecs_kr', '_codecs_tw', '_collections',
'_collections_abc', '_colorize', '_compat_pickle', '_compression', '_contextvars',
'_csv', '_datetime', '_functools', '_heapq', '_imp', '_interpchannels', '_interpqueues',
'_interpreters', '_io', '_ios_support', '_json', '_locale', '_lsprof', '_markupbase',
'_md5', '_multibytecodec', '_opcode', '_opcode_metadata', '_operator', '_osx_support',
'_pickle', '_py_abc', '_pydatetime', '_pydecimal', '_pyio', '_pylong', '_pyrepl',
'_random', '_sha1', '_sha2', '_sha3', '_signal', '_sitebuiltins', '_sre', '_stat',
'_statistics', '_string', '_strptime', '_struct', '_suggestions', '_symtable', '_sysconfig',
'_thread', '_threading_local', '_tokenize', '_tracemalloc', '_typing', '_warnings', '_weakref',
'_weakrefset', '_winapi', 'abc', 'antigravity', 'argparse', 'array', 'ast', 'asyncio',
'atexit', 'base64', 'bdb', 'binascii', 'bisect', 'builtins', 'bz2', 'cProfile', 'calendar',
'cmath', 'cmd', 'code', 'codecs', 'codeop', 'collections', 'colorsys', 'compileall',
'concurrent', 'configparser', 'contextlib', 'contextvars', 'copy', 'copyreg', 'csv',
'ctypes', 'curses', 'dataclasses', 'datetime', 'dbm', 'decimal', 'difflib', 'dis',
'doctest', 'email', 'encodings', 'ensurepip', 'enum', 'errno', 'faulthandler', 'filecmp',
'fileinput', 'fnmatch', 'fractions', 'ftplib', 'functools', 'gc', 'genericpath', 'getopt',
'getpass', 'gettext', 'glob', 'graphlib', 'gzip', 'hashlib', 'heapq', 'hmac', 'html', 'http',
'idlelib', 'imaplib', 'importlib', 'inspect', 'io', 'ipaddress', 'itertools', 'json', 'keyword',
'linecache', 'locale', 'logging', 'lzma', 'mailbox', 'marshal', 'math', 'mimetypes', 'mmap',
'modulefinder', 'msvcrt', 'multiprocessing', 'netrc', 'nt', 'ntpath', 'nturl2path', 'numbers',
'opcode', 'operator', 'optparse', 'os', 'pathlib', 'pdb', 'pickle', 'pickletools', 'pkgutil',
'platform', 'plistlib', 'poplib', 'posixpath', 'pprint', 'profile', 'pstats', 'pty', 'py_compile',
'pyclbr', 'pydoc', 'pydoc_data', 'queue', 'quopri', 'random', 're', 'reprlib', 'rlcompleter',
'runpy', 'sched', 'secrets', 'selectors', 'shelve', 'shlex', 'shutil', 'signal', 'site',
'smtplib', 'socket', 'socketserver', 'sqlite3', 'sre_compile', 'sre_constants', 'sre_parse',
'ssl', 'stat', 'statistics', 'string', 'stringprep', 'struct', 'subprocess', 'symtable',
'sys', 'sysconfig', 'tabnanny', 'tarfile', 'tempfile', 'test', 'textwrap', 'this', 'threading',
'time', 'timeit', 'tkinter', 'token', 'tokenize', 'tomllib', 'trace', 'traceback', 'tracemalloc',
'tty', 'turtle', 'turtledemo', 'types', 'typing', 'unittest', 'urllib', 'uuid', 'venv', 'warnings',
'wave', 'weakref', 'webbrowser', 'winreg', 'wsgiref', 'xml', 'xmlrpc', 'xxsubtype', 'zipapp',
'zipfile', 'zipimport', 'zlib', 'zoneinfo']
def set_active_view(view_name: str):
st.session_state["active_view"] = view_name
def validate_repo_format(repo_url):
"""Validate that the repository URL is in the correct format."""
pattern = r"^https://github\.com/[^/]+/[^/]+/?$"
if re.match(pattern, repo_url):
return True
return False
def validate_requirements(uploaded_requirements):
# First read the requirements.yaml content
try:
content = uploaded_requirements.read().decode("utf-8")
data = yaml.safe_load(content)
if not isinstance(data, dict) or "dependencies" not in data:
return False, "The requirements file must contain a 'dependencies' key with a list of dependencies."
dependencies = data["dependencies"]
if not isinstance(dependencies, list):
return False, "The 'dependencies' key must be a list."
for dep in dependencies:
if not isinstance(dep, str):
return False, f"Dependency '{dep}' is not a string."
else:
# Only allow fixed version dependencies in the format 'package==version'
if not re.match(r"^[a-zA-Z0-9_.-]+==[a-zA-Z0-9_.-]+$", dep):
return False, f"Dependency '{dep}' is not in the correct format. Only fixed versions with 'package==version' are allowed."
return True, "Requirements file is valid."
except Exception as e:
return False, f"Error reading requirements file: {e}"
def validate_submission(submitted_info):
"""Ensure required inputs exist and meet basic quality checks."""
errors = []
project_name = submitted_info.get("project_name", "").strip()
if not project_name:
errors.append("Project name is required.")
else:
if len(project_name) < 3:
errors.append("Project name must be at least 3 characters long.")
elif len(project_name) > 50:
errors.append("Project name must be at most 50 characters long.")
elif not re.match(r"^[A-Za-z0-9 _.-]+$", project_name):
errors.append("Project name contains invalid characters. Only letters, numbers, spaces, underscores, hyphens, and periods are allowed.")
elif project_name.lower() in (name.lower() for name in st.session_state["stdlib_modules"]):
errors.append(f"Project name '{project_name}' cannot be the same as an existing Python standard library module. This would break some of the LabConstrictor functionalities. Please choose a different name.")
project_version = submitted_info.get("project_version", "").strip()
if not project_version:
errors.append("Project version is required.")
else:
semver_pattern = r"^\d+\.\d+\.\d+(-[0-9A-Za-z-.]+)?(\+[0-9A-Za-z-.]+)?$"
if not re.match(semver_pattern, project_version):
errors.append("Project version must follow semantic versioning (e.g., 1.0.0).")
if uploaded_icon := submitted_info.get("icon_uploaded"):
if uploaded_icon.size > MAX_FILE_SIZE_MB * 1024 * 1024:
errors.append(f"Icon file '{uploaded_icon.name}' exceeds {MAX_FILE_SIZE_MB} MB limit.")
if uploaded_welcome := submitted_info.get("welcome_uploaded"):
if uploaded_welcome.size > MAX_FILE_SIZE_MB * 1024 * 1024:
errors.append(f"Welcome file '{uploaded_welcome.name}' exceeds {MAX_FILE_SIZE_MB} MB limit.")
if uploaded_headers := submitted_info.get("headers_uploaded"):
if uploaded_headers.size > MAX_FILE_SIZE_MB * 1024 * 1024:
errors.append(f"Headers file '{uploaded_headers.name}' exceeds {MAX_FILE_SIZE_MB} MB limit.")
if not errors:
st.session_state["ready_for_pr"] = True
else:
st.session_state["ready_for_pr"] = False
return errors
def reset_tool_versions():
for key in ("jupyterlab_version", "notebook_version", "matplotlib_version"):
if key in st.session_state:
del st.session_state[key]
def get_authenticated_username(token):
headers = {
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.github+json"
}
response = requests.get("https://api.github.com/user", headers=headers)
if response.status_code == 200:
return response.json().get("login", "user")
else:
raise RuntimeError(f"❌ Could not retrieve GitHub username: {response.status_code} — {response.text}")
def has_changes_to_commit(path, cwd):
try:
status = run_git_command(["status", "--porcelain", str(path)], cwd=cwd)
return bool(status.strip())
except Exception as e:
st.write(f"⚠️ Could not check changes: {e}")
return False
def run_git_command(args, cwd=None, github_token=None):
git_cmd = ["git"]
env = None
if github_token:
sanitized_token = github_token.strip()
if sanitized_token:
basic_token = base64.b64encode(
f"x-access-token:{sanitized_token}".encode("utf-8")
).decode("ascii")
auth_value = f"Basic {basic_token}"
git_cmd.extend(["-c", f"http.extraHeader=Authorization: {auth_value}"])
env = os.environ.copy()
env["GIT_HTTP_AUTHORIZATION"] = auth_value
result = subprocess.run(
git_cmd + args, cwd=cwd, capture_output=True, text=True, env=env
)
if result.returncode != 0:
raise RuntimeError(f"❌ Git error running 'git {' '.join(args)}':\n{result.stderr.strip()}")
return result.stdout.strip()
def push_config_changes_to_new_branch(
folder, branch_prefix, commit_message, github_token, repo_path
):
try:
username = get_authenticated_username(github_token)
timestamp = datetime.now().strftime("%Y%m%d%H%M")
new_branch = f"{branch_prefix}/{username}-{timestamp}"
run_git_command(["config", "user.email", f"{username}@users.noreply.github.com"], cwd=repo_path)
run_git_command(["config", "user.name", username], cwd=repo_path)
run_git_command(["checkout", "main"], cwd=repo_path)
run_git_command(["pull", "origin", "main"], cwd=repo_path, github_token=github_token)
if not has_changes_to_commit(folder, cwd=repo_path):
st.write(f"ℹ️ No changes detected in `{folder}`. Nothing to push.")
return None
else:
st.write(f"✅ Changes detected!")
run_git_command(["checkout", "-b", new_branch], cwd=repo_path)
run_git_command(["add", folder], cwd=repo_path)
run_git_command(["commit", "-m", commit_message], cwd=repo_path)
run_git_command(
["push", "--set-upstream", "origin", new_branch],
cwd=repo_path,
github_token=github_token,
)
st.write(f"✅ Successfully pushed to branch `{new_branch}`.")
return new_branch
except Exception as e:
st.write(f"❌ Failed to push changes: {e}")
return None
def create_pull_request(from_branch, title, body, github_repo_url, github_token):
try:
repo_url = github_repo_url.strip().rstrip('/')
github_owner, github_repo_name = repo_url.split('/')[-2:]
api_url = f"https://api.github.com/repos/{github_owner}/{github_repo_name}/pulls"
headers = {
"Accept": "application/vnd.github+json",
"Authorization": f"Bearer {github_token.strip()}"
}
payload = {
"title": title,
"head": from_branch,
"base": "main",
"body": body,
"maintainer_can_modify": True
}
response = requests.post(api_url, headers=headers, json=payload)
if response.status_code == 201:
pr_url = response.json()["html_url"]
st.write(f"✅ Pull request correctly created!")
return response.json()
elif response.status_code == 422 and "already exists" in response.text:
st.write(f"ℹ️ Pull request already exists for branch `{from_branch}`. It has been automatically updated.")
return None
else:
st.write(f"❌ Failed to create pull request: {response.status_code} — {response.text}")
return None
except Exception as e:
st.write(f"❌ Error creating PR: {e}")
return None
def push_and_create_pr(folder, branch_prefix,
commit_message, pr_title, pr_body,
github_repo_url, github_token,
repo_path):
branch = push_config_changes_to_new_branch(
folder=folder,
branch_prefix=branch_prefix,
commit_message=commit_message,
github_token=github_token,
repo_path=repo_path
)
if branch:
return create_pull_request(
from_branch=branch,
title=pr_title,
body=pr_body,
github_repo_url=github_repo_url,
github_token=github_token
)
return None
# Handle Windows permission issues with .git directories
def handle_remove_error(func, path, exc_info):
if not os.access(path, os.W_OK):
os.chmod(path, stat.S_IWUSR | stat.S_IRUSR)
func(path)
else:
raise exc_info[1]
def replace_in_file(file_path, old, new):
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
content = content.replace(old, str(new).strip())
with open(file_path, 'w', encoding='utf-8') as file:
file.write(content)
def capture_yaml_key_lines(yaml_text: str, key: str):
"""Return all lines whose trimmed content starts with '<key>:'."""
prefix = f"{key}:"
captured = []
for line in yaml_text.splitlines():
stripped = line.lstrip()
if stripped.startswith(prefix):
indent = line[: len(line) - len(stripped)]
captured.append(f"{indent}{stripped}")
return captured
def restore_yaml_duplicate_keys(serialized_text: str, key: str, preserved_lines):
"""Replace the serialized '<key>:' line with the preserved lines (i.e., duplicates)."""
if not preserved_lines:
return serialized_text
key_prefix = f"{key}:"
output_lines = []
inserted = False
for line in serialized_text.splitlines():
stripped = line.lstrip()
if stripped.startswith(key_prefix):
if not inserted:
output_lines.extend(preserved_lines)
inserted = True
continue
output_lines.append(line)
if not inserted:
output_lines.extend(preserved_lines)
if serialized_text.endswith("\n"):
return "\n".join(output_lines) + "\n"
return "\n".join(output_lines)
def create_icns(img, output_path):
# Function taken from: https://github.com/jojomondag/PNG_to_ico_to_icns_converter/blob/main/PNG_to_ico_to_icns_converter.py
# Define the icon types and sizes
icon_sizes = {
'icp4': (16, 16), # 16x16
'icp5': (32, 32), # 32x32
'icp6': (64, 64), # 64x64
'ic07': (128, 128), # 128x128
'ic08': (256, 256), # 256x256
'ic09': (512, 512), # 512x512
'ic10': (1024, 1024), # 1024x1024
}
icns_data = b''
for icon_type, size in icon_sizes.items():
# Use different interpolation methods depending on size
if size[0] <= 32: # For very small sizes, use NEAREST for crispness
resized_img = img.resize(size, Image.NEAREST)
else: # For larger sizes, use LANCZOS for better quality
resized_img = img.resize(size, Image.LANCZOS)
# Save the image to PNG format in memory
png_data_io = BytesIO()
resized_img.save(png_data_io, format='PNG')
png_data = png_data_io.getvalue()
# Build the icon block
icon_block = icon_type.encode('utf-8') + struct.pack('>I', len(png_data) + 8) + png_data
icns_data += icon_block
# ICNS header
icns_header = b'icns' + struct.pack('>I', len(icns_data) + 8)
with open(output_path, 'wb') as f:
f.write(icns_header)
f.write(icns_data)
def initialize_project(repo_path, project_name, version, hide_code,
welcome_image_path, header_image_path, icon_image_path,
ico_image_path, icns_image_path,
github_owner, github_repo_name):
# Copy and replace template files into their final locations
template_to_location = {
".tools/templates/hide_code_cells.py": "app/python_scripts/hide_code_cells.py"
}
for template_path, final_path in template_to_location.items():
shutil.copyfile(repo_path / template_path, repo_path / final_path)
# Define the conversion dictionary
proyectname_lower = project_name.lower()
conversion_dict = {
"LOWER_PROJ_NAME": {
"environment.yaml": proyectname_lower,
".tools/templates/download_executable_template.md": proyectname_lower,
},
"PYTHON_PROJ_NAME": {
"setup.py": proyectname_lower.replace(" ", "_").replace("-", "_").replace(".", "_"),
".tools/docs/external_code_upload.md": proyectname_lower.replace(" ", "_").replace("-", "_").replace(".", "_"),
".tools/templates/Welcome_template.ipynb": proyectname_lower.replace(" ", "_").replace("-", "_").replace(".", "_"),
},
"UNDERSCORED_PROJECT_NAME": {
"construct.yaml": project_name.replace(" ", "_"),
"app/bash_bat_scripts/pre_uninstall.bat": project_name.replace(" ", "_"),
"app/bash_bat_scripts/post_install.bat": project_name.replace(" ", "_"),
},
"PROJECT_NAME": {
"construct.yaml": project_name,
"app/menuinst/notebook_launcher.json": project_name,
"app/bash_bat_scripts/post_install.bat": project_name,
"app/bash_bat_scripts/post_install.sh": project_name,
"app/bash_bat_scripts/pre_uninstall.bat": project_name,
"app/bash_bat_scripts/pre_uninstall.sh": project_name,
"app/bash_bat_scripts/uninstall.sh": project_name,
".tools/templates/Welcome_template.ipynb": project_name,
".tools/templates/download_executable_template.md": project_name,
".tools/python/bump_constructor.py": project_name,
},
"VERSION_NUMBER": {
"construct.yaml": version,
"app/bash_bat_scripts/post_install.bat": version,
".tools/templates/download_executable_template.md": version,
"setup.py": version,
},
"WELCOME_IMAGE": {
"construct.yaml": welcome_image_path,
},
"HEADER_IMAGE": {
"construct.yaml": header_image_path,
},
"ICON_IMAGE": {
"construct.yaml": icon_image_path,
},
"GITHUB_OWNER": {
"app/bash_bat_scripts/post_install.bat": github_owner,
".tools/templates/download_executable_template.md": github_owner,
},
"GITHUB_REPO_NAME": {
".tools/templates/download_executable_template.md": github_repo_name,
},
"HIDE_CODE_DISABLED": {
"app/python_scripts/hide_code_cells.py": hide_code,
}
}
# Replace placeholders in files
for placeholder, files in conversion_dict.items():
for file_path, replacement in files.items():
replace_in_file(repo_path / file_path, placeholder, replacement)
# Update the notebook launcher JSON file to set the icons if needed
notebook_launcher_path = repo_path / "app" / "menuinst" / "notebook_launcher.json"
if notebook_launcher_path.exists():
with open(notebook_launcher_path, "r", encoding="utf-8") as f:
launcher_data = f.read()
if icon_image_path:
launcher_data = launcher_data.replace("ICON_IMAGE_PATH", f"BASE_PATH_KEYWORD/{project_name}/{icon_image_path.name}")
else:
launcher_data = launcher_data.replace("ICON_IMAGE_PATH", f"")
if ico_image_path:
launcher_data = launcher_data.replace("ICON_ICO_IMAGE_PATH", f"BASE_PATH_KEYWORD/{project_name}/{ico_image_path.name}")
else:
launcher_data = launcher_data.replace("ICON_ICO_IMAGE_PATH", f"")
if icns_image_path:
launcher_data = launcher_data.replace("ICON_ICNS_IMAGE_PATH", f"BASE_PATH_KEYWORD/{project_name}/{icns_image_path.name}")
else:
launcher_data = launcher_data.replace("ICON_ICNS_IMAGE_PATH", f"")
with open(notebook_launcher_path, "w", encoding="utf-8") as f:
f.write(launcher_data)
# Update the construct.yaml extra_files to include the images if they were provided
# Read the construct.yaml to check if images need to be set
construct_path = repo_path / "construct.yaml"
construct_raw_text = construct_path.read_text(encoding="utf-8")
post_install_lines = capture_yaml_key_lines(construct_raw_text, "post_install")
pre_uninstall_lines = capture_yaml_key_lines(construct_raw_text, "pre_uninstall")
construct_data = yaml.safe_load(construct_raw_text)
if construct_data is None:
construct_data = {}
extra_files = construct_data.get("extra_files")
if extra_files is None:
extra_files = []
construct_data["extra_files"] = extra_files
# Check if the welcome, header, icon images were provided and in case they were not, set them to empty in the construct.yaml
if not welcome_image_path:
construct_data.pop("welcome_image", None)
if not header_image_path:
construct_data.pop("header_image", None)
if not icon_image_path:
construct_data.pop("icon_image", None)
# Normalize existing entries into a dict for quick lookup
existing_sources = set()
existing_dests = set()
normalized_items = []
for item in extra_files:
# Items can be either dicts (k: v) or strings with mapping? Assume dicts per example
if isinstance(item, dict):
for src, dst in item.items():
existing_sources.add(str(src))
existing_dests.add(str(dst))
normalized_items.append({str(src): str(dst)})
else:
# If strings are present, keep them
normalized_items.append(item)
# Check if the images paths are provided and not already in the list¨
image_mappings = [ icon_image_path, ico_image_path, icns_image_path ]
for src_path in image_mappings:
if src_path:
dest_path = f"{project_name}/{src_path.name}"
if src_path and str(src_path) not in existing_sources and dest_path not in existing_dests:
normalized_items.append({str(src_path): dest_path})
# Optionally sort entries (dicts by their single key) for determinism
def sort_key(item):
if isinstance(item, dict):
# single-key dict
k = next(iter(item.keys()))
return (0, k)
return (1, str(item))
normalized_items.sort(key=sort_key)
construct_data["extra_files"] = normalized_items
# Write back the updated construct.yaml
construct_serialized = yaml.dump(construct_data, sort_keys=False)
construct_serialized = restore_yaml_duplicate_keys(
construct_serialized, "post_install", post_install_lines
)
construct_serialized = restore_yaml_duplicate_keys(
construct_serialized, "pre_uninstall", pre_uninstall_lines
)
construct_path.write_text(construct_serialized, encoding="utf-8")
def enqueue_pull_request(repo_url, personal_access_token, input_dict):
github_owner, github_repo_name = repo_url.rstrip('/').split('/')[-2:]
st.write(f"### Creating pull request for {github_repo_name}...")
# Download the GitHub repo, create a branch, add files, open a PR, etc.
if "repo_path" in st.session_state and (st.session_state["repo_path"] / ".git").exists():
st.write(f"✅ Git repo already cloned at {st.session_state['repo_path']}")
else:
st.session_state["repo_path"] = Path.cwd() / github_repo_name
if (st.session_state["repo_path"] / ".git").exists():
st.write(f"🧹 Removing existing folder at {st.session_state['repo_path']}...")
shutil.rmtree(st.session_state["repo_path"], onerror=handle_remove_error)
st.write(f"🌀 Cloning Git repo to {st.session_state['repo_path']}...")
try:
run_git_command(
["clone", repo_url, str(st.session_state["repo_path"])],
github_token=personal_access_token,
)
except RuntimeError as clone_error:
raise RuntimeError(f"❌ Git clone failed: {clone_error}") from clone_error
st.write(f"✅ Git repo cloned at {st.session_state['repo_path']}")
st.write("🛠 Initialising project files...")
if input_dict["submission_mode"] == "initialize":
logo_folder_path = st.session_state["repo_path"] / "app" / "logo"
logo_folder_path.mkdir(parents=True, exist_ok=True)
icon_path, ico_path, icns_path, welcome_path, headers_path = "", "", "", "", ""
# Convert the uploaded icon PNg to ICO format and
if input_dict["icon_uploaded"]:
icon_path = Path("app") / "logo" / input_dict["icon_uploaded"].name
ico_path = Path("app") / "logo" / input_dict["icon_uploaded"].name.replace(".png", ".ico")
icns_path = Path("app") / "logo" / input_dict["icon_uploaded"].name.replace(".png", ".icns")
with open(st.session_state["repo_path"] / icon_path, "wb") as f:
f.write(input_dict["icon_uploaded"].getbuffer())
# Load the uploaded image
ico_logo = Image.open(input_dict["icon_uploaded"])
# Save as ICO
ico_logo.save(st.session_state["repo_path"] / ico_path,
format='ICO', sizes=[(16,16), (32,32), (64,64), (128,128), (256,256)])
# Save as ICNS
create_icns(ico_logo, st.session_state["repo_path"] / icns_path)
# First move the uploaded files to the repo path under the app/logo
if input_dict["welcome_uploaded"]:
welcome_path = Path("app") / "logo" / input_dict["welcome_uploaded"].name
with open(st.session_state["repo_path"] / welcome_path, "wb") as f:
f.write(input_dict["welcome_uploaded"].getbuffer())
if input_dict["headers_uploaded"]:
headers_path = Path("app") / "logo" / input_dict["headers_uploaded"].name
with open(st.session_state["repo_path"] / headers_path, "wb") as f:
f.write(input_dict["headers_uploaded"].getbuffer())
# Then initialize the project files by replacing placeholders
initialize_project(
repo_path=st.session_state["repo_path"],
project_name=input_dict["project_name"],
version=input_dict["project_version"],
hide_code=input_dict["hide_code"],
welcome_image_path=welcome_path,
header_image_path=headers_path,
icon_image_path=icon_path,
ico_image_path=ico_path,
icns_image_path=icns_path,
github_owner=github_owner,
github_repo_name=github_repo_name,
)
# Also, check if there is a README.md file and if so move it to the '.tools/docs' folder and create a new one with the project name
readme_path = st.session_state["repo_path"] / "README.md"
# Check if README.md exists
if readme_path.exists():
# Check if it's the README from LabConstrictor template
readme_content = readme_path.read_text(encoding="utf-8")
if "# LabConstrictor" in readme_content:
docs_folder = st.session_state["repo_path"] / ".tools" / "docs"
docs_folder.mkdir(parents=True, exist_ok=True)
# Move the existing README.md to docs folder
shutil.move(str(readme_path), str(docs_folder / "README.md"))
# Replace any occurence of '.tools/docs to . as we have moved the README.md there
replace_in_file(docs_folder / "README.md", ".tools/docs", ".")
# Create a new README.md with the project name
with open(readme_path, "w", encoding="utf-8") as f:
f.write(f"# {input_dict['project_name']}\n\n")
f.write("Welcome to CellPatcher!\n")
f.write("This repository was initialised using LabConstrictor.\n")
f.write(f"If you want to start using {input_dict['project_name']}, please go to the [How to Download and Install {input_dict['project_name']}?](#how-to-download-and-install-{input_dict['project_name'].lower()}) below.\n")
f.write(f"> If you are the developer of {input_dict['project_name']}, please customise this README file.\n")
f.write("\n")
f.write(f"## How to Download and Install {input_dict['project_name']}?\n\n")
f.write(f"The installer would only be available once {input_dict['project_name']} developer has created a release.\n")
f.write(f"Please, go to [this page](.tools/docs/download_executable.md) and check if the installing instructions are there.\n")
f.write(f"In case there is no documentation there, please [create an issue](https://github.com/{input_dict['github_owner']}/{input_dict['github_repo_name']}/issues) asking the developer to create a release.\n")
f.write(f"## Documentation for {input_dict['project_name']}'s Developers\n\n")
f.write("Internal documentation on how to upload notebooks or create executables is available in the [.tools/docs](.tools/docs/README.md) folder.\n")
f.write("\n")
# Create a pull request using GitHub CLI
pr_title = f"Pull request for {input_dict['project_name']} initialisation"
pr_body = f"This pull request customises raw LabConstrictor template to include the project name {input_dict['project_name']} v{input_dict['project_version']}."
commit_message = f"Initisalise repository as {input_dict['project_name']} v{input_dict['project_version']}"
elif input_dict["submission_mode"] == "update":
uploads = input_dict.get("queued_uploads")
if not uploads:
uploads = [
{
"notebook_uploaded": input_dict["notebook_uploaded"],
"requirements_uploaded": input_dict["requirements_uploaded"],
}
]
normalized_uploads = []
required_upload_keys = {"notebook_name", "notebook_bytes", "requirements_name", "requirements_bytes"}
for upload in uploads:
if required_upload_keys <= set(upload.keys()):
normalized_uploads.append(upload)
elif "notebook_uploaded" in upload and "requirements_uploaded" in upload:
normalized_uploads.append(
{
"notebook_name": upload["notebook_uploaded"].name,
"notebook_bytes": bytes(upload["notebook_uploaded"].getbuffer()),
"requirements_name": upload["requirements_uploaded"].name,
"requirements_bytes": bytes(upload["requirements_uploaded"].getbuffer()),
}
)
else:
raise ValueError("Notebook submission payload is missing file content.")
notebook_names = []
for upload in normalized_uploads:
notebook_name = upload["notebook_name"]
# The requirements file must be named 'requirements.yaml' to be correctly processed in the repo, but we can allow some flexibility in the upload naming and just rename it here
requirements_name = "requirements.yaml" # upload["requirements_name"]
notebook_names.append(notebook_name)
notebook_path = (
st.session_state["repo_path"] / "notebooks" / Path(notebook_name).stem
)
notebook_path.mkdir(parents=True, exist_ok=True)
with open(notebook_path / notebook_name, "wb") as f:
f.write(upload["notebook_bytes"])
with open(notebook_path / requirements_name, "wb") as f:
f.write(upload["requirements_bytes"])
if len(notebook_names) == 1:
pr_title = f"Upload/Update notebook {notebook_names[0]}"
pr_body = (
f"This pull request uploads/updates the notebook {notebook_names[0]} "
"and the requirements file."
)
commit_message = (
f"Upload/Update notebook {notebook_names[0]} and requirements"
)
else:
notebook_list = "\n".join(f"- {name}" for name in notebook_names)
pr_title = f"Upload/Update {len(notebook_names)} notebooks"
pr_body = (
"This pull request uploads/updates the following notebooks:\n"
f"{notebook_list}"
)
commit_message = f"Upload/Update {len(notebook_names)} notebooks"
response = push_and_create_pr(
folder=st.session_state["repo_path"],
branch_prefix="submission",
commit_message=commit_message,
pr_title=pr_title,
pr_body=pr_body,
github_repo_url=repo_url,
github_token=personal_access_token,
repo_path=st.session_state["repo_path"]
)
st.write(f"🧹 Cleaning the repo {st.session_state['repo_path']}.")
shutil.rmtree(st.session_state["repo_path"], onerror=handle_remove_error)
st.write(f"✅ Cleaned up the repo.")
if response is None:
st.write("❌ Finished!")
else:
st.write("🏆 Finished!")
st.write("### 👣 Next steps")
st.write("Everything went well and your pull request is ready.")
if input_dict["submission_mode"] == "initialize":
st.write(f"Please go back to [documentation]({repo_url}/blob/main/.tools/docs/initialise_repository.md) to know how to accept the Pull Request.")
else:
st.write(f"Please go back to [documentation]({repo_url}/blob/main/.tools/docs/accept_pull_request.md) to continue with the Notebook upload/update.")
st.write(f"If you want to go directly to the pull request, click here: {response['html_url']}")
st.write("After the pull request is accepted you can close this Streamlit app and start working on your project! 🚀")
return response
def mark_submission_dirty():
st.session_state["ready_for_pr"] = False
def render_sidebar_content(current_view: str):
with st.sidebar:
if current_view == VIEW_INITIALIZE:
st.header("Submission tips")
st.markdown(
"""
- Zip large folders before uploading.
- Pick the interpreter version that matches your `pyproject.toml` or `runtime.txt`.
- Keep uploads below 25 MB each to avoid browser time-outs.
"""
)
elif current_view == VIEW_UPDATE:
st.header("Update tips")
st.info(
"Update workflow details will live here soon. Use the back button "
"if you want to switch actions."
)
else:
st.header("Get started")
st.write("Pick what you would like to do on the main panel to continue.")
st.markdown(
"""
- Initialising a brand new LabConstrictor repository.
- Or prepare to update an existing deployment (coming soon).
"""
)
def render_welcome_view():
# Always reset readiness state
st.session_state["ready_for_pr"] = False
st.title("Welcome to LabConstrictor! 🐍")
st.write("Below you can initialise your GitHub repository or upload/update a notebook to your existing project.")
col1, col2 = st.columns(2)
with col1:
st.subheader("Initialise GitHub repository")
st.write("After creating a repository using the LabConstrictor template, you can initialise it here.")
st.button(
"Start initialisation",
use_container_width=True,
on_click=set_active_view,
args=(VIEW_INITIALIZE,),
)
with col2:
st.subheader("Upload/Update a notebook")
st.write("Upload/Update a notebook and a requirements.yaml file to update an existing project.")
st.button(
"Upload/Update notebook",
use_container_width=True,
on_click=set_active_view,
args=(VIEW_UPDATE,),
)
def render_initialize_view():
st.button(
"<- Back to welcome",
key="back_to_welcome_init",
on_click=set_active_view,
args=(VIEW_WELCOME,),
)
st.title("LabConstrictor - Repository initialiser")
st.write("Once you have created a GitHub repository using the LabConstrictor template, you can use this form to initialise it with your project details.")
st.write("Please fill:")
st.write("- Project name: We recommend using the same name as your GitHub repository.")
st.write("- Initial project version: We recommend starting at version 0.0.1.")
st.write(f"- Optionally disable automatic code hiding in notebooks. By default, LabConstrictor hides code cells in the notebooks. If you are wondering what this means, please check [this documentation](https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/code_hiding.md).")
st.write("- Optionally upload images to customize your executable interface.")
st.write("Then, click on `Validate submission`.")
runtime_container = st.container()
with runtime_container:
st.subheader("*Project basic info")
project_name = st.text_input("Project name",
placeholder="Cool Analytics API",
on_change=mark_submission_dirty)
project_version = st.text_input("Initial project version",
placeholder="0.0.1",
help="Specify the initial version of the project.",
on_change=mark_submission_dirty)
hide_code = st.checkbox("Disable automatic code hiding in notebooks",
value=False,
help="If checked, the code hiding feature will be disabled in the generated executable.",
on_change=mark_submission_dirty)
st.subheader("(Optional) Upload project images")
uploaded_icon = st.file_uploader(
"Project icon image (resized to 256 x 256 px)",
accept_multiple_files=False,
type="png",
help=f"",
on_change=mark_submission_dirty,
)
uploaded_welcome = st.file_uploader(
"Project welcome image (resized to 164 x 314 px)",
accept_multiple_files=False,
type="png",
help=f"",
on_change=mark_submission_dirty,
)
uploaded_headers = st.file_uploader(
"Project headers image (resized to 150 x 57 px)",
accept_multiple_files=False,
type="png",
help=f"",
on_change=mark_submission_dirty,
)
submitted = st.button("Validate submission", use_container_width=True)
if submitted:
st.session_state["submitted_info"] = {
"submission_mode": "initialize",
"project_name": project_name,
"project_version": project_version,
"hide_code": hide_code,
"icon_uploaded": uploaded_icon,
"welcome_uploaded": uploaded_welcome,
"headers_uploaded": uploaded_headers,
}
validation_errors = validate_submission(st.session_state["submitted_info"])
if validation_errors:
validation_error_list_text = ['\n - ' + e for e in validation_errors]
st.error(f"Please fix the following before resubmitting: {''.join(validation_error_list_text)}")
st.session_state["ready_for_pr"] = False
else:
st.success(
f"Project '{project_name.strip()}' was submitted successfully!"
)
st.session_state["ready_for_pr"] = True
if st.session_state["ready_for_pr"]:
st.subheader("⬆️ Upload it to GitHub")
st.write("Now that your `📃 Submission list` looks good, provide:")
st.write(" - Your GitHub repository URL")
st.write(" - Your Personal Access Token (check this [guide](https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/personal_access_token.md) on how to create one)")
st.write("Then, click on `🚀 Create pull request` and wait for the instructions on the output.")
repo_url = st.text_input(
"GitHub repository URL",
key="github_repo_url",
placeholder="https://github.com/org/repo",
help="Paste the repository where the pull request should be opened.",
)
token = st.text_input(
"Personal Access Token",
key="pat",
type="password",
help="Provide a GitHub Personal Access Token with repo permissions.",
)
create_pr = st.button(
"Create pull request",
disabled=not repo_url.strip(),
use_container_width=True,
icon="🚀",
)
if create_pr:
# First validate the PAT
if not token.strip():
st.error("Please provide a Personal Access Token.")
return
elif not token.strip().startswith("ghp_"):
if token.strip().startswith("github_pat_"):
st.error("It seems you provided a **Fine-grained GitHub token**. This type of token is currently not supported. Please create and provide a **Personal Access Token (classic)** with the `ghp_` prefix. Check this [guide](https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/personal_access_token.md) on how to create one.")
return
else:
st.error("The provided token does not seem to be a valid **Personal Access Token (classic)**. Please ensure it starts with `ghp_` and has the necessary permissions. Check this [guide](https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/personal_access_token.md) on how to create one.")
return
# Then validate the repo URL format
if validate_repo_format(repo_url.strip()):
with st.status("Creating pull request...", expanded=True) as status:
try:
enqueue_pull_request(repo_url.strip(), token.strip(), st.session_state["submitted_info"])
except Exception as e:
status.error(f"Failed to create PR:\n{e}")
else:
st.error("Please ensure that your repository URL is in the correct format (e.g., https://github.com/org/repo).")
def render_update_view():
st.button(
"<- Back to welcome",
key="back_to_welcome_update",
on_click=set_active_view,
args=(VIEW_WELCOME,),
)
st.title("Upload/Update notebooks on an existing project")
st.write("Once you have initialised the repository, you are ready to start uploading notebooks.")
st.write("Here are the quick steps for uploading, but remember you have a more documented [upload guidelines from LabConstrictor](https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/notebook_upload.md).")
st.write("1. Upload a notebook and a requirements yaml file by drag and dropping or by browsing it on your computer.")
st.write("2. Click on `➕ Validate & Add submission`. This will validate the notebook and requirement, and in case it passes, it will be added to the `📃 Submission list`.")
st.write("3. If you want to upload/update more notebooks, repeat steps 1 and 2. You can add or remove as many notebooks as you want to the `📃 Submission list`.")
st.write("4. Once your `📃 Submission list` is ready, go to the `⬆️ Upload it to GitHub` section,provide your GitHub repository URL and Personal Access Token, and click on `🚀 Create pull request`.")
st.write("5. Wait for the instructions on the output and check your pull request in GitHub to see the next steps to merge it and have your notebooks live in your project!")
queued_uploads = st.session_state["update_upload_queue"]
form_key = st.session_state["update_upload_form_key"]
uploaded_notebook = st.file_uploader(
"Jupyter Notebook file (.ipynb)",
key=f"uploaded_notebook_{form_key}",
accept_multiple_files=False,
type="ipynb",
help=f"",
on_change=mark_submission_dirty,
)
st.write("If you need help to obtain the requirements file, check this [guide](https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/notebook_requirements.md).")
uploaded_requirements = st.file_uploader(
"Requirements yaml file (requirements.yaml)",
key=f"uploaded_requirements_{form_key}",
accept_multiple_files=False,
type="yaml",
help=f"This file can be created using following the [guide](https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/notebook_requirements.md).",
on_change=mark_submission_dirty,
)
submitted = st.button("Validate & Add Submission", use_container_width=True, type="secondary", icon="➕")
if submitted:
if not uploaded_notebook:
st.error("Please upload a Jupyter Notebook file.")
elif not uploaded_requirements:
st.error("Please upload a requirements yaml file.")
else:
validation_flag, validation_msg = validate_requirements(uploaded_requirements)
if uploaded_requirements is not None:
uploaded_requirements.seek(0)
if uploaded_notebook is not None:
uploaded_notebook.seek(0)
if not validation_flag:
st.error(f"Requirements file validation failed: {validation_msg}")
else:
notebook_already_in_queue = False
for upload in queued_uploads:
if upload["notebook_name"] == uploaded_notebook.name:
# If the notebook was already on the list it would get updated
upload.update({
"notebook_name": uploaded_notebook.name,
"notebook_bytes": bytes(uploaded_notebook.getbuffer()),
"requirements_name": uploaded_requirements.name,