-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterface.py
More file actions
5724 lines (4421 loc) · 191 KB
/
interface.py
File metadata and controls
5724 lines (4421 loc) · 191 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
import streamlit as st
import re
import urllib.request
import pandas as pd
import json
import ssl
import os
import subprocess
from datetime import datetime
from pathlib import Path
import time
import socket
import streamlit.components.v1 as components
import shutil
import zipfile
import requests
import io
import tempfile
import html
from streamlit_scroll_to_top import scroll_to_here
# base directory where all project-related data wiil be stored
BASE_PATH = "/data"
os.makedirs(BASE_PATH, exist_ok=True)
# diretory used to store project history
HISTORY_DIR = "/contribute_history"
os.makedirs(HISTORY_DIR, exist_ok=True)
# file JSON that keeps track of all projects and their states
DB_FILE = os.path.join(HISTORY_DIR, "projects_history.json")
# --- GENERAL FUNCTIONS ---
def load_local_db():
"""Loads the history from the JSON file if it exists."""
if os.path.exists(DB_FILE):
try:
with open(DB_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except Exception as e:
st.error(f"Error loading history: {e}")
return {}
def save_local_db():
"""Saves the current state of projects_db to the disk."""
try:
with open(DB_FILE, "w", encoding="utf-8") as f:
json.dump(st.session_state.projects_db, f, indent=4)
except Exception as e:
st.error(f"Error saving data: {e}")
def prepare_submission_folder(project):
"""Prepare a clean 'for_submission' folder."""
project_dir = Path(BASE_PATH) / project
submission_dir = project_dir / "for_submission"
submission_dir.mkdir(exist_ok=True)
# -----------------------------
# 1. MOVE FILES
# -----------------------------
exclude = {"for_submission", "test_data"}
for item in project_dir.iterdir():
if item.name in exclude:
continue
dst = submission_dir / item.name
if item.is_file():
shutil.move(str(item), str(dst))
# -----------------------------
# 2. HANDLE TEST DATA
# -----------------------------
ptype = st.session_state.get("project_type", None)
# skip test packaging for external images without Dockerfile
if ptype != "from_image_without_df":
test_dir = project_dir / "test_data"
submission_test_dir = submission_dir / "test_data"
input_src = test_dir / "data"
output_src = test_dir / "results"
input_dst = submission_test_dir / "input_test_data"
output_dst = submission_test_dir / "output_test_data"
input_dst.mkdir(parents=True, exist_ok=True)
output_dst.mkdir(parents=True, exist_ok=True)
# INPUT FILES
input_files = list(input_src.glob("*"))
if len(input_files) == 1:
# single file -> copy directly
shutil.copy(input_files[0], input_dst / input_files[0].name)
elif len(input_files) > 1:
# multiple files -> zip them
zip_path = input_dst / f"{project}.zip"
with zipfile.ZipFile(zip_path, "w") as z:
for f in input_files:
z.write(f, arcname=f.name)
# OUTPUT -> always zipped
output_zip = output_dst / f"{project}_output.zip"
with zipfile.ZipFile(output_zip, "w") as z:
for f in output_src.glob("*"):
z.write(f, arcname=f.name)
return submission_dir
# --- HELPER FUNCTION FOR ONTOLOGY ---
def get_ontology_path(term_id, terms_map, relations):
"""Builds the 'Parent > Child' path recursively for intuitive visualization."""
if not term_id:
return ""
path = [terms_map.get(term_id, term_id)]
current_id = term_id
# 10-level limit to prevent infinite recursion in case of errors in the .obo file
for _ in range(10):
parent_id = relations.get(current_id)
if not parent_id or parent_id not in terms_map:
break
path.insert(0, terms_map[parent_id])
current_id = parent_id
return " > ".join(path)
def apply_primary_button_style():
"""Apply custom styling to Streamlit primary buttons"""
st.markdown("""
<style>
button[kind="primary"] {
background-color: #059669 !important;
color: white !important;
border: none !important;
}
button[kind="primary"]:hover {
background-color: #047857 !important;
}
button[kind="primary"]:active {
background-color: #065f46 !important;
}
button[kind="primary"][disabled],
button[kind="primary"]:disabled {
background-color: #9ca3af !important;
color: #e5e7eb !important;
cursor: not-allowed !important;
opacity: 0.6 !important;
transform: none !important;
box-shadow: none !important;
}
button[kind="primary"][disabled]:hover {
background-color: #9ca3af !important;
}
</style>
""", unsafe_allow_html=True)
# --- FUNCTION TO READ ONTOLOGY FROM GITHUB ---
@st.cache_data(ttl=3600)
def get_remote_dio_data():
"""
Fetch ontology data from GitHub:
- dio.obo -> terms + hierarchy
- dio.diaf -> tool mappings
"""
ontology = {}
relations = {}
diaf_data = []
context = ssl._create_unverified_context()
# 1. Load dio.obo (ID -> Name + relations)
try:
obo_url = "https://raw.githubusercontent.com/pegi3s/dockerfiles/master/metadata/dio.obo"
with urllib.request.urlopen(obo_url, context=context) as response:
content = response.read().decode("utf-8")
term_id = None
for line in content.splitlines():
line = line.strip()
if line.startswith("id:"):
term_id = line.split("id:")[1].strip()
elif line.startswith("name:") and term_id:
ontology[term_id] = line.split("name:")[1].strip()
elif line.startswith("is_a:") and term_id:
parent_id = line.split("is_a:")[1].split()[0].strip()
relations[term_id] = parent_id
elif line == "":
term_id = None
except Exception as e:
print(f"Error loading dio.obo: {e}")
# 2. Load dio.diaf
try:
diaf_url = "https://raw.githubusercontent.com/pegi3s/dockerfiles/master/metadata/dio.diaf"
with urllib.request.urlopen(diaf_url, context=context) as response:
content = response.read().decode("utf-8")
for line in content.splitlines():
if "\t" in line:
parts = line.split("\t")
diaf_data.append({"id": parts[0].strip(), "tool": parts[1].strip()})
except Exception as e:
print(f"Error loading dio.diaf: {e}")
return ontology, relations, diaf_data
# --- REMOTE FILE FETCHING ---
@st.cache_data(ttl=3600)
def fetch_dockerfile(project, version):
"""Fetch Dockerfile from the repository."""
BASE_URL = "https://raw.githubusercontent.com/pegi3s/dockerfiles/master"
paths = [
(f"{BASE_URL}/{project}/{version}/Dockerfile", True, False),
(f"{BASE_URL}/{project}/{version}/dockerfile", True, True),
(f"{BASE_URL}/{project}/Dockerfile", False, False),
(f"{BASE_URL}/{project}/dockerfile", False, True)
]
for url, use_version, use_lower in paths:
try:
res = requests.get(url)
if res.status_code == 200:
return res.text, url, use_version, use_lower
except:
pass
return "", None, None, None
@st.cache_data(ttl=3600)
def fetch_readme(project, version):
"""Fetch README.md from the repository."""
BASE_URL = "https://raw.githubusercontent.com/pegi3s/dockerfiles/master"
paths = [
(f"{BASE_URL}/{project}/{version}/README.md", True),
(f"{BASE_URL}/{project}/README.md", False)
]
for url, use_version in paths:
try:
res = requests.get(url)
if res.status_code == 200:
return res.text, url, use_version
except:
pass
return "", None, None
@st.cache_data(ttl=3600)
def get_remote_metadata():
"""Fetch global metadata.json from the repository."""
try:
url = "https://raw.githubusercontent.com/pegi3s/dockerfiles/master/metadata/metadata.json"
context = ssl._create_unverified_context()
with urllib.request.urlopen(url, context=context) as response:
data = json.loads(response.read().decode())
return data
except Exception as e:
print(f"Error fetching metadata: {e}")
return []
def get_project_metadata(project_name):
"""Retrieve metadata for a specific project."""
data = get_remote_metadata()
if isinstance(data, list):
for item in data:
if item.get("name") == project_name:
return item
elif isinstance(data, dict):
return data.get(project_name)
return {}
def build_docker_image(project, project_dir):
build_cmd = [
"docker",
"build",
"-t",
project.lower(),
str(project_dir),
]
progress_bar = st.progress(0)
status_text = st.empty()
log_lines = []
process = subprocess.Popen(
build_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
universal_newlines=True
)
progress = 0
for line in iter(process.stdout.readline, ""):
if line.strip():
log_lines.append(line)
progress = min(progress + 1, 95)
progress_bar.progress(progress)
status_text.text(line.strip())
process.stdout.close()
process.wait()
progress_bar.progress(100)
full_log = "".join(log_lines)
with st.expander("📄 Build Log"):
st.code(full_log)
return process.returncode == 0, log_lines
# --- MAPPING BETWEEN README AND METADATA ---
METADATA_TO_README = {
"tool_name": "tool_name", # special (lower + no spaces)
"tool_url": "source_url",
"tool_url_help": "manual_url",
"source_url": "source_url",
"manual_url": "manual_url",
}
README_TO_METADATA = {
"tool_name": "tool_name", # special (format back)
"source_url": "tool_url",
"manual_url": "tool_url_help",
"source_url": "source_url",
"manual_url": "manual_url",
}
def normalize_toolname(value):
"""Convert tool name to metadata format (lowercase, no spaces)"""
if not value:
return value
return value.replace(" ", "").lower()
def prettify_toolname(value):
"""Convert tool name to display format (README)"""
if not value:
return value
return value.capitalize()
def prefill_if_empty(target, source, mapping, direction):
"""Fill target fields with values from source if they are empty."""
for target_field, source_field in mapping.items():
current_val = target.get(target_field)
# skip if already has a real value
if current_val is not None and str(current_val).strip() != "":
continue
val = source.get(source_field)
if not val or not str(val).strip():
continue
# special case: tool name formatting
if target_field == "tool_name":
if direction == "readme_to_metadata":
val = normalize_toolname(val)
elif direction == "metadata_to_readme":
val = prettify_toolname(val)
target[target_field] = val
# --- DIRTY STATE MANAGEMENT ---
DIRTY_SECTIONS = ["dockerfile", "readme", "metadata", "ontology", "test_instructions"]
def dirty_key(section):
"""Generate session_state key for dirty tracking."""
return f"{section}_dirty"
def mark_dirty(section, current, saved):
"""Mark a section as dirty if current value differs from saved value."""
key = dirty_key(section)
is_dirty = current != saved
st.session_state[key] = is_dirty
return is_dirty
def set_section_clean(section):
"""Mark a section as clean (no unsaved changes)."""
st.session_state[dirty_key(section)] = False
def is_section_dirty(section):
"""Check if a section has unsaved changes."""
return st.session_state.get(dirty_key(section), False)
# --- NAVIGATION CONTROL ---
def navigation_guard(target_page):
"""Prevent navigation if there are unsaved changes."""
dirty_sections = [
s for s in DIRTY_SECTIONS
if is_section_dirty(s)
]
if dirty_sections:
show_unsaved_dialog(target_page)
st.stop()
change_page(target_page)
st.rerun()
def autosave_dirty_sections():
"""Automatically persist any modified sections before navigation."""
project = st.session_state.get("active_project")
if not project or project not in st.session_state.projects_db:
return
p_data = st.session_state.projects_db[project]
saved_any = False
# --- DOCKERFILE ---
dockerfile_key = f"dockerfile_{project}"
if dockerfile_key in st.session_state:
dockerfile_value = st.session_state[dockerfile_key]
elif st.session_state.get("current_page") == "Dockerfile":
dockerfile_value = st.session_state.get("dockerfile_temp", p_data.get("dockerfile", ""))
else:
dockerfile_value = p_data.get("dockerfile", "")
if is_section_dirty("dockerfile") or dockerfile_value != p_data.get("dockerfile", ""):
p_data["dockerfile"] = dockerfile_value
set_section_clean("dockerfile")
saved_any = True
# --- README ---
readme_manual_key = f"readme_manual_{project}"
readme_key = f"readme_{project}"
if readme_manual_key in st.session_state:
readme_value = st.session_state[readme_manual_key]
elif readme_key in st.session_state:
readme_value = st.session_state[readme_key]
else:
readme_value = p_data.get("readme_raw", p_data.get("readme", ""))
if is_section_dirty("readme") or readme_value != p_data.get("readme", ""):
p_data["readme"] = readme_value
p_data["readme_raw"] = readme_value
set_section_clean("readme")
saved_any = True
# --- METADATA ---
raw_json = st.session_state.get(
f"metadata_json_raw_{project}",
p_data.get("metadata_json_raw", "")
)
if is_section_dirty("metadata") or raw_json != p_data.get("metadata_json_raw", ""):
try:
parsed = json.loads(raw_json)
except json.JSONDecodeError:
p_data["metadata_invalid_raw"] = raw_json
st.session_state[f"metadata_json_raw_{project}"] = raw_json
save_local_db()
st.error("Cannot autosave Metadata because the JSON is invalid. Please fix it before using the sidebar.")
st.stop()
p_data["metadata_json"] = parsed
p_data["metadata_preview_json"] = parsed
p_data["metadata_json_raw"] = raw_json
p_data.pop("metadata_invalid_raw", None)
set_section_clean("metadata")
saved_any = True
# --- ONTOLOGY ---
if is_section_dirty("ontology"):
selected_terms = [
key.replace("ontology_", "", 1)
for key, value in st.session_state.items()
if key.startswith("ontology_") and value is True
]
p_data["ontology_terms"] = selected_terms
set_section_clean("ontology")
saved_any = True
# --- TEST INSTRUCTIONS ---
test_instructions = st.session_state.get(
f"test_instructions_{project}",
p_data.get("test_instructions", "")
)
if is_section_dirty("test_instructions") or test_instructions != p_data.get("test_instructions", ""):
p_data["test_instructions"] = test_instructions
set_section_clean("test_instructions")
saved_any = True
if saved_any:
save_local_db()
st.toast("Changes autosaved.")
def sidebar_navigation(target_page):
"""Navigate via sidebar with autosave."""
autosave_dirty_sections()
change_page(target_page)
st.rerun()
def discard_unsaved_section_changes():
"""Discard all unsaved changes and restore last saved state."""
project = st.session_state.get("active_project")
if not project or project not in st.session_state.projects_db:
for section in DIRTY_SECTIONS:
set_section_clean(section)
return
p_data = st.session_state.projects_db[project]
# --- DOCKERFILE ---
if is_section_dirty("dockerfile"):
for key in [f"dockerfile_{project}", "dockerfile_temp"]:
if key in st.session_state:
del st.session_state[key]
# --- README ---
if is_section_dirty("readme"):
saved_readme = p_data.get("readme", "")
p_data["readme_raw"] = saved_readme
p_data["readme_source"] = "saved"
for key in [f"readme_{project}", f"readme_manual_{project}"]:
if key in st.session_state:
del st.session_state[key]
# --- METADATA ---
if is_section_dirty("metadata"):
saved_metadata = p_data.get("metadata_json", {})
saved_metadata_raw = json.dumps(saved_metadata, indent=4, ensure_ascii=False) if saved_metadata else ""
p_data["metadata_preview_json"] = saved_metadata
p_data["metadata_json_raw"] = saved_metadata_raw
p_data["metadata_source"] = "saved"
metadata_raw_key = f"metadata_json_raw_{project}"
if metadata_raw_key in st.session_state:
del st.session_state[metadata_raw_key]
# --- ONTOLOGY ---
if is_section_dirty("ontology"):
for key in list(st.session_state.keys()):
if key.startswith("ontology_"):
del st.session_state[key]
# --- TEST INSTRUCTIONS ---
if is_section_dirty("test_instructions"):
key = f"test_instructions_{project}"
if key in st.session_state:
del st.session_state[key]
# Reset all dirty flags
for section in DIRTY_SECTIONS:
set_section_clean(section)
@st.dialog("⚠️ Unsaved Changes")
def show_unsaved_dialog(target_page):
"""Confirmation dialog shown when user tries to leave with unsaved changes."""
st.warning("You have unsaved changes. Are you sure you want to leave this page?")
col1, col2 = st.columns(2)
if col1.button("✅ Yes, leave without saving", use_container_width=True):
discard_unsaved_section_changes()
st.session_state["show_dialog"] = False
change_page(target_page)
st.rerun()
if col2.button("❌ Cancel", use_container_width=True):
st.session_state["show_dialog"] = False
st.rerun()
def nav_button(label, target_page, **kwargs):
"""Navigation button with guard against unsaved changes."""
if st.button(label, **kwargs):
navigation_guard(target_page)
def nav_button_sidebar(label, target_page, **kwargs):
"""Navigation button with guard against unsaved changes."""
if st.sidebar.button(label, **kwargs):
navigation_guard(target_page)
# 1. PAGE CONFIGURATION
st.set_page_config(page_title="pegi3s BDIP", layout="wide")
@st.cache_data(ttl=3600)
def get_remote_built_list():
"""
Fetch list of already built tools from remote metadata.
Returns a sorted list of tool names.
"""
try:
url = "https://raw.githubusercontent.com/pegi3s/dockerfiles/master/metadata/metadata.json"
context = ssl._create_unverified_context()
with urllib.request.urlopen(url, context=context) as response:
data = json.loads(response.read().decode())
if isinstance(data, list):
return sorted([str(item.get("name", "Unknown")) for item in data])
elif isinstance(data, dict):
return sorted(list(data.keys()))
return []
except Exception as e:
print(f"Detailed error: {e}")
return []
def change_page(name):
"""Update current page in session state."""
st.session_state.current_page = name
scroll()
@st.dialog("⚠️ Reset All Data")
def confirm_reset_dialog():
"""
Confirm dialog to delete all projects and local data.
Requires explicit user confirmation ("DELETE").
"""
st.warning("This will **permanently delete ALL projects**.")
st.caption("This action cannot be undone.")
confirm = st.text_input(
"Type DELETE to confirm",
key="reset_confirm"
)
col1, col2 = st.columns(2)
# Cancel action
if col1.button("Cancel", use_container_width=True):
st.rerun()
# Delete action (only enabled if confirmed)
delete_disabled = confirm != "DELETE"
if col2.button(
"Delete All",
use_container_width=True,
disabled=delete_disabled,
type="primary"
):
st.session_state.projects_db = {}
st.session_state.active_project = None
# remove local database file
if os.path.exists(DB_FILE):
os.remove(DB_FILE)
change_page("Home")
st.rerun()
def sidebar_nave():
"""Sidebar navigation component."""
page_options = [
"Create Project",
"Current Project",
"Dockerfile",
"README",
"Metadata",
"Ontology",
"Build and Test",
"Status",
]
# Button Back to Home
nav_button_sidebar("← Back to Home", "Home")
current_index = (
page_options.index(st.session_state.current_page)
if st.session_state.current_page in page_options
else 0
)
selected_page = st.sidebar.radio("Navigate to:", page_options, index=current_index)
if selected_page != st.session_state.current_page:
sidebar_navigation(selected_page)
st.sidebar.divider()
# reset button
if st.sidebar.button("🗑️ Reset All Data", use_container_width=True):
confirm_reset_dialog()
def get_progress(status_str):
"""Extract progress ratio -> "X/Y"."""
try:
if "/" in status_str:
done, total = status_str.split(" ")[0].split("/")
return int(done) / int(total)
except:
pass
return 0.0
def get_type_color(ptype):
"""
Return color associated with project type.
Used for UI badges and styling.
"""
if ptype == "from_image_df":
return "#5ba3d3" #blue
elif ptype == "from_image_without_df":
return "#8669d6" #purple
elif ptype == "update":
return "#e6962f" #orange
else:
return "#28BD66" #green (regular)
def format_type_label(ptype):
"""Convert internal project type to user-friendly label."""
if ptype == "from_image_df":
return "From Image (Dockerfile)"
elif ptype == "from_image_without_df":
return "From Image (No Dockerfile)"
elif ptype == "update":
return "Update"
else:
return "Regular"
def get_current_project_type():
"""Retrieve current project type."""
project = st.session_state.get("active_project")
if not project:
return st.session_state.get("project_type", "regular")
return st.session_state.projects_db.get(project, {}).get("project_type", "regular")
# --- NAV HANDLER ---
if "nav" not in st.session_state:
st.session_state.nav = None
nav_event = components.html(
"""
<script>
window.addEventListener("message", (event) => {
if (event.data && event.data.page) {
const url = new URL(window.location);
url.searchParams.set("page", event.data.page);
window.location.href = url.toString();
}
});
</script>
""",
height=0,
)
# --- QUERY PARAM NAVIGATION ---
query_params = st.query_params
if "page" in query_params:
st.session_state.current_page = query_params["page"]
if "current_page" not in st.session_state:
st.session_state.current_page = "Home"
if "projects_db" not in st.session_state:
st.session_state.projects_db = load_local_db()
if "active_project" not in st.session_state:
st.session_state.active_project = None
if "test_success" not in st.session_state:
st.session_state.test_success = False
st.session_state.built_list = get_remote_built_list()
if 'scroll_to_top' not in st.session_state:
st.session_state.scroll_to_top = False
if st.session_state.scroll_to_top:
scroll_to_here(0, key='top')
st.session_state.scroll_to_top = False
def scroll():
st.session_state.scroll_to_top = True
# --- HOME PAGE ---
if st.session_state.current_page == "Home":
# CSS styling
st.markdown("""
<style>
[data-testid="stSidebar"] {display: none;}
.block-container {
max-width: 1100px;
margin: auto;
padding-top: 2rem;
}
.hero-title {
font-size: 52px;
font-weight: 700;
text-align: center;
letter-spacing: -1px;
}
.hero-sub {
font-size: 22px;
text-align: center;
margin-bottom: 30px;
opacity: 0.8;
}
@keyframes fadeInUp {
from { opacity: 0; transform: translateY(25px); }
to { opacity: 1; transform: translateY(0); }
}
.card-link {
text-decoration: none !important;
color: inherit !important;
display: block;
-webkit-tap-highlight-color: transparent;
}
.card-link:hover,
.card-link:visited,
.card-link:active {
text-decoration: none !important;
color: inherit !important;
}
.card-title {
color: inherit;
}
.card-sub {
color: inherit;
opacity: 0.7;
}
/* Card-like buttons */
div.stButton > button {
height: 200px;
width: 100%;
border-radius: 16px;
border: 1px solid rgba(59,130,246,0.15);
background: linear-gradient(
145deg,
rgba(59,130,246,0.04),
rgba(255,255,255,0.02)
);
backdrop-filter: blur(8px);
padding: 25px;
text-align: center;
color: inherit;
transition: all 0.25s ease;
display: flex;
flex-direction: column;
justify-content: center;
opacity: 0;
animation: fadeInUp 0.5s ease forwards;
}
/* Button text styling */
div.stButton > button p {
margin: 0;
}
div.stButton > button p:nth-of-type(1) {
font-size: 28px;
}
div.stButton > button p:nth-of-type(2) {
font-size: 20px;
font-weight: 600;
margin-top: 10px;
color: inherit;
}
div.stButton > button p:nth-of-type(3) {
font-size: 13px;
opacity: 0.7;
margin-top: 6px;
}
/* Hover effect */
div.stButton > button:hover {
border: 1px solid #3b82f6;
box-shadow: 0 10px 30px rgba(59,130,246,0.25);
transform: translateY(-6px) scale(1.02);
background: linear-gradient(
145deg,
rgba(59,130,246,0.10),
rgba(59,130,246,0.05)
);
}
/* Click effect */
div.stButton > button:active {
transform: scale(0.96);
}
/* Staggered animation */
div.stButton:nth-of-type(1) > button { animation-delay: 0.2s; }
div.stButton:nth-of-type(2) > button { animation-delay: 0.35s; }
div.stButton:nth-of-type(3) > button { animation-delay: 0.5s; }
</style>
""", unsafe_allow_html=True)
# --- Title ---
st.markdown('<div class="hero-title">pegi3s BDIP</div>', unsafe_allow_html=True)
st.markdown(
'<div class="hero-sub">Contribution Platform</div>', unsafe_allow_html=True
)
st.caption(
"Select a workflow to begin your contribution or validation process:"
)
# --- Main actions ---
col1, col2 = st.columns(2)
with col1:
if st.button(
"🚀\n\nStart New Project\n\nCreate a new Docker image submission with full workflow.",
use_container_width=True,
):
st.session_state.current_page = "Create Project"
st.rerun()
with col2:
if st.button(
"⚙️\n\nTest Docker Image\n\nRun and validate an existing Docker image.",
use_container_width=True,
):
st.session_state.current_page = "Test Docker Image"
st.rerun()
# --- Command to download test input data ---