-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
3748 lines (3139 loc) Β· 154 KB
/
Copy pathapp.py
File metadata and controls
3748 lines (3139 loc) Β· 154 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
"""
DNA Data Storage Platform
A user-friendly platform for encoding, randomizing, decoding, and comparing DNA-based data storage.
"""
import streamlit as st
import time
import os
from io import BytesIO
# Import custom modules
from dna_codec import (
encode_to_dna, decode_from_dna, validate_dna_sequence,
calculate_encoding_density
)
from compression import (
detect_file_type, compress_data, decompress_data,
get_compression_stats, TEXT_EXTENSIONS, IMAGE_EXTENSIONS, PDF_EXTENSIONS,
AUDIO_EXTENSIONS, VIDEO_EXTENSIONS, get_pdf_info, get_audio_info, get_audio_compression_suggestion,
get_video_info, get_video_compression_suggestion
)
from randomization import (
calculate_dna_characteristics, randomize_dna, derandomize_dna,
verify_randomization, calculate_randomization_improvement,
ChaosSystem, get_chaos_system_info, list_chaos_systems
)
from comparison import (
compare_data, format_comparison_results, detect_comparison_type
)
# Page configuration
st.set_page_config(
page_title="DNA Data Storage Platform v2",
page_icon="π§¬",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS
st.markdown("""
<style>
.main-header {
font-size: 2.5rem;
color: #1E88E5;
text-align: center;
margin-bottom: 1rem;
}
.sub-header {
font-size: 1.2rem;
color: #666;
text-align: center;
margin-bottom: 2rem;
}
.metric-card {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 1rem;
border-radius: 10px;
color: white;
text-align: center;
}
.dna-preview {
font-family: 'Courier New', monospace;
background-color: #f0f4f8;
padding: 1rem;
border-radius: 5px;
word-break: break-all;
max-height: 300px;
overflow-y: auto;
}
.success-box {
background-color: #d4edda;
border: 1px solid #c3e6cb;
padding: 1rem;
border-radius: 5px;
color: #155724;
}
.info-box {
background-color: #e7f3ff;
border: 1px solid #b8daff;
padding: 1rem;
border-radius: 5px;
color: #004085;
}
.stTabs [data-baseweb="tab-list"] {
gap: 8px;
}
.stTabs [data-baseweb="tab"] {
height: 50px;
padding: 10px 20px;
background-color: #f0f2f6;
border-radius: 5px;
}
.stTabs [aria-selected="true"] {
background-color: #1E88E5;
color: white;
}
</style>
""", unsafe_allow_html=True)
def init_session_state():
"""Initialize session state variables."""
if 'encoded_dna' not in st.session_state:
st.session_state.encoded_dna = None
if 'encoded_metadata' not in st.session_state:
st.session_state.encoded_metadata = {}
if 'randomized_dna' not in st.session_state:
st.session_state.randomized_dna = None
if 'decoded_data' not in st.session_state:
st.session_state.decoded_data = None
if 'decoded_metadata' not in st.session_state:
st.session_state.decoded_metadata = {}
if 'original_filename' not in st.session_state:
st.session_state.original_filename = None
if 'original_data' not in st.session_state:
st.session_state.original_data = None
if 'example_encoded' not in st.session_state:
st.session_state.example_encoded = False
if 'ngs_fragments' not in st.session_state:
st.session_state.ngs_fragments = None
if 'ngs_settings' not in st.session_state:
st.session_state.ngs_settings = {}
def main():
"""Main application."""
init_session_state()
# Header
st.markdown('<h1 class="main-header">𧬠DNA Data Storage Platform v2</h1>', unsafe_allow_html=True)
st.markdown('<p style="text-align: center; color: #666; margin-bottom: 2rem;">Store any data format in DNA sequences with compression, randomization, and NGS preparation</p>', unsafe_allow_html=True)
# Mode selection tabs
tab1, tab2, tab3, tab4, tab5, tab6 = st.tabs([
"π€ Encode",
"π Randomization",
"π§« NGS Prep",
"π₯ Decode",
"π Comparison",
"π Guide"
])
with tab1:
encode_mode()
with tab2:
randomization_mode()
with tab3:
ngs_preparation_mode()
with tab4:
decode_mode()
with tab5:
comparison_mode()
with tab6:
guide_mode()
# Footer
st.markdown("---")
st.markdown(
'<p style="text-align: center; color: #888;">DNA Data Storage Platform v2.0 | '
'Encoding density: 2 bits/nucleotide</p>',
unsafe_allow_html=True
)
def encode_mode():
"""Encode mode: Upload file and encode to DNA sequence."""
st.header("π€ Encode Mode")
st.markdown("Upload a file and encode it into a DNA sequence.")
col1, col2 = st.columns([1, 1])
with col1:
st.subheader("π Input")
# File upload
uploaded_file = st.file_uploader(
"Upload a file (any format)",
type=None,
key="encode_upload",
help="Supported: Text, Images, and any binary files"
)
if uploaded_file:
file_data = uploaded_file.read()
filename = uploaded_file.name
file_ext = os.path.splitext(filename)[1].lower()
file_type = detect_file_type(filename, file_data)
# Store original data for comparison
st.session_state.original_data = file_data
st.session_state.original_filename = filename
# File info display
st.markdown("##### π File Information")
info_col1, info_col2 = st.columns(2)
with info_col1:
st.metric("File Name", filename)
st.metric("File Size", f"{len(file_data):,} bytes")
with info_col2:
st.metric("File Extension", file_ext or "None")
st.metric("Detected Type", file_type.title())
st.markdown("---")
# Compression options
st.markdown("##### βοΈ Encoding Parameters")
compression_option = st.radio(
"Compression",
options=["None", "Data-Type-Specific"],
horizontal=True,
help="None: Raw encoding | Data-Type-Specific: Brotli for text, WebP for images, Object optimization for PDF"
)
# Compression quality controls
brotli_quality = 11 # default
webp_quality = 85 # default
pdf_image_dpi = 150 # default
pdf_image_quality = 85 # default
pdf_method_code = 'pdf_opt' # default
audio_method_code = 'flac' # default
audio_bitrate = 192 # default
video_method_code = 'h264' # default
video_crf = 23 # default
video_preset = 'medium' # default
if compression_option == "Data-Type-Specific":
if file_type == 'text' or file_type == 'binary':
st.info("π **Text/Binary detected** - Will use Brotli compression")
brotli_quality = st.slider(
"Brotli Quality Level",
min_value=0,
max_value=11,
value=11,
help="0 = fastest (less compression) | 11 = best compression (slower). Higher values remove more redundancy."
)
st.caption(f"Quality {brotli_quality}: {'Maximum compression' if brotli_quality == 11 else 'Faster encoding' if brotli_quality < 5 else 'Balanced'}")
elif file_type == 'image':
st.info("πΌοΈ **Image detected** - Will use WebP compression")
webp_quality = st.slider(
"WebP Quality Level",
min_value=1,
max_value=100,
value=85,
help="1 = maximum compression (more artifacts) | 100 = lossless quality. Lower values remove more visual information."
)
st.caption(f"Quality {webp_quality}: {'High compression (lossy)' if webp_quality < 50 else 'Balanced quality' if webp_quality < 90 else 'Near-lossless'}")
elif file_type == 'pdf':
st.info("π **PDF detected** - Choose compression method")
# Show PDF info
pdf_info = get_pdf_info(file_data)
with st.expander("π PDF Details", expanded=False):
col_a, col_b = st.columns(2)
with col_a:
st.metric("Pages", pdf_info['page_count'])
st.metric("Has Images", "Yes" if pdf_info['has_images'] else "No")
with col_b:
st.metric("Has Text", "Yes" if pdf_info['has_text'] else "No")
if pdf_info['metadata'].get('title'):
st.metric("Title", pdf_info['metadata']['title'][:20])
# Method selection
st.markdown("**π§ Compression Method**")
pdf_method = st.radio(
"Select Method",
options=["Object Optimization (pdf_opt)", "Image Downsampling (pdf_gs)"],
horizontal=True,
index=0,
help="pdf_opt: Lossless cleanup | pdf_gs: Lossy image compression"
)
# Map selection to method code
pdf_method_code = 'pdf_opt' if 'pdf_opt' in pdf_method else 'pdf_gs'
if pdf_method_code == 'pdf_opt':
st.markdown("---")
st.markdown("**π Object Optimization** (Lossless)")
st.caption("β Remove unused objects")
st.caption("β Flatten structure")
st.caption("β Compress streams")
st.success("β‘ **No quality settings** - This method preserves ALL content exactly as-is")
st.caption("π‘ Best for: Text-heavy PDFs, legal documents, forms")
# Set defaults (won't affect output for pdf_opt)
pdf_image_dpi = 150
pdf_image_quality = 85
else: # pdf_gs
st.markdown("---")
st.markdown("**πΌοΈ Image Downsampling** (Lossy)")
st.caption("β Reduces image resolution")
st.caption("β Recompresses images")
st.caption("β Maximum file size reduction")
# Single quality slider
pdf_quality = st.slider(
"Compression Quality",
min_value=1,
max_value=100,
value=50,
help="1 = Maximum compression (lowest quality) | 100 = Minimum compression (best quality)"
)
# Map single slider to DPI and JPEG quality
# Quality 1-33: Aggressive (72 DPI, 40-70% JPEG)
# Quality 34-66: Balanced (150 DPI, 70-85% JPEG)
# Quality 67-100: Quality (300 DPI, 85-95% JPEG)
if pdf_quality <= 33:
pdf_image_dpi = 72
pdf_image_quality = 40 + int((pdf_quality / 33) * 30) # 40-70
quality_label = "β‘ Aggressive"
quality_desc = "Maximum compression, noticeable quality loss"
elif pdf_quality <= 66:
pdf_image_dpi = 150
pdf_image_quality = 70 + int(((pdf_quality - 33) / 33) * 15) # 70-85
quality_label = "βοΈ Balanced"
quality_desc = "Good compression, suitable for screens"
else:
pdf_image_dpi = 300
pdf_image_quality = 85 + int(((pdf_quality - 66) / 34) * 10) # 85-95
quality_label = "π¨ Quality"
quality_desc = "Minimal compression, suitable for printing"
st.caption(f"{quality_label}: {quality_desc}")
with st.expander("π Technical Details"):
st.caption(f"Image Resolution: {pdf_image_dpi} DPI")
st.caption(f"JPEG Quality: {pdf_image_quality}%")
if not pdf_info['has_images']:
st.warning("βΉοΈ No images detected - compression benefit may be limited")
elif file_type == 'audio':
st.info("π΅ **Audio detected** - Choose compression method")
# Show audio info
audio_info = get_audio_info(file_data)
with st.expander("π Audio Details", expanded=False):
col_a, col_b = st.columns(2)
with col_a:
if audio_info['duration']:
mins = int(audio_info['duration'] // 60)
secs = int(audio_info['duration'] % 60)
st.metric("Duration", f"{mins}:{secs:02d}")
if audio_info['sample_rate']:
st.metric("Sample Rate", f"{audio_info['sample_rate']:,} Hz")
if audio_info['bitrate']:
st.metric("Bitrate", f"{audio_info['bitrate']} kbps")
with col_b:
if audio_info['channels']:
ch_name = "Stereo" if audio_info['channels'] == 2 else "Mono" if audio_info['channels'] == 1 else f"{audio_info['channels']}ch"
st.metric("Channels", ch_name)
if audio_info['codec']:
st.metric("Codec", audio_info['codec'].upper())
quality_tier = audio_info.get('quality_tier', 'unknown')
tier_emoji = {'lossless': 'πΌ', 'high': 'π§', 'medium': 'π΅', 'low': 'π»', 'very_low': 'π’'}.get(quality_tier, 'β')
st.metric("Quality", f"{tier_emoji} {quality_tier.replace('_', ' ').title()}")
# Get compression suggestion
suggestion = get_audio_compression_suggestion(audio_info)
# Show suggestion
st.markdown("---")
st.markdown("**π‘ Recommended Compression**")
method_names = {
'flac': 'FLAC (Lossless)',
'aac': 'AAC (Lossy - Efficient)',
'mp3': 'MP3 (Lossy - Universal)'
}
rec_method = suggestion['method']
rec_bitrate = suggestion.get('bitrate', 192)
if suggestion.get('warning'):
st.warning(f"β οΈ {suggestion['warning']}")
st.success(f"β¨ **{method_names.get(rec_method, rec_method)}** - {suggestion['reason']}")
# Method selection
st.markdown("**π§ Compression Method**")
# Build options list
method_options = ["FLAC (Lossless)", "AAC (Lossy)", "MP3 (Lossy)"]
default_idx = {'flac': 0, 'aac': 1, 'mp3': 2}.get(rec_method, 1)
audio_method = st.radio(
"Select Method",
options=method_options,
horizontal=True,
index=default_idx,
help="FLAC: Perfect quality | AAC: Efficient at low bitrates | MP3: Universal compatibility"
)
# Map selection to method code
audio_method_code = 'flac' if 'FLAC' in audio_method else ('aac' if 'AAC' in audio_method else 'mp3')
if audio_method_code == 'flac':
st.markdown("---")
st.markdown("**πΌ FLAC** (Free Lossless Audio Codec)")
st.caption("β Lossless - Perfect reconstruction")
st.caption("β Typically 50-70% of original WAV size")
st.caption("β Preserves studio quality for archiving")
if audio_info.get('is_lossless') and not audio_info.get('is_compressed'):
st.success("β‘ **Ideal choice** - FLAC is perfect for uncompressed audio like WAV/AIFF")
elif audio_info.get('is_lossless') and audio_info.get('is_compressed'):
st.warning("β οΈ File is already lossless compressed - FLAC may not reduce size further")
else:
st.warning("β οΈ File is already lossy compressed - FLAC will likely INCREASE file size")
audio_bitrate = 0 # Not used for FLAC
elif audio_method_code == 'aac':
st.markdown("---")
st.markdown("**π§ AAC** (Advanced Audio Coding)")
st.caption("β More efficient than MP3 at same bitrate")
st.caption("β Better quality at low bitrates (64-128 kbps)")
st.caption("β Native support on Apple devices and modern browsers")
# Determine default bitrate based on suggestion
default_bitrate = rec_bitrate if rec_method == 'aac' else 128
# Bitrate selection
bitrate_preset = st.select_slider(
"Audio Quality",
options=["Low (64 kbps)", "Medium (96 kbps)", "Good (128 kbps)", "High (192 kbps)", "Best (256 kbps)"],
value=f"Good (128 kbps)" if default_bitrate <= 128 else f"High (192 kbps)",
help="Higher bitrate = better quality, larger file"
)
bitrate_map = {
"Low (64 kbps)": 64,
"Medium (96 kbps)": 96,
"Good (128 kbps)": 128,
"High (192 kbps)": 192,
"Best (256 kbps)": 256
}
audio_bitrate = bitrate_map[bitrate_preset]
# Quality description
quality_tier = audio_info.get('quality_tier', 'unknown')
if quality_tier in ('low', 'very_low'):
st.info(f"π‘ Original is {quality_tier.replace('_', ' ')} quality - AAC is optimal for further compression")
elif quality_tier == 'medium':
st.info("π‘ AAC 128kbps β MP3 160kbps in quality")
else: # mp3
st.markdown("---")
st.markdown("**π΅ MP3** (MPEG Audio Layer III)")
st.caption("β Universal compatibility")
st.caption("β Works on all devices and players")
st.caption("β Best for maximum compatibility")
# Bitrate selection
bitrate_preset = st.select_slider(
"Audio Quality",
options=["Low (96 kbps)", "Medium (128 kbps)", "Good (192 kbps)", "High (256 kbps)", "Best (320 kbps)"],
value="Good (192 kbps)",
help="Higher bitrate = better quality, larger file"
)
bitrate_map = {
"Low (96 kbps)": 96,
"Medium (128 kbps)": 128,
"Good (192 kbps)": 192,
"High (256 kbps)": 256,
"Best (320 kbps)": 320
}
audio_bitrate = bitrate_map[bitrate_preset]
# Quality description
quality_tier = audio_info.get('quality_tier', 'unknown')
if quality_tier in ('low', 'very_low'):
st.warning(f"β οΈ Original is {quality_tier.replace('_', ' ')} quality ({audio_info.get('bitrate', '?')} kbps) - Consider AAC for better efficiency at low bitrates")
elif file_type == 'video':
st.info("π¬ **Video detected** - Choose compression method")
# Show video info
video_info = get_video_info(file_data)
with st.expander("π Video Details", expanded=False):
col_a, col_b = st.columns(2)
with col_a:
if video_info['duration']:
mins = int(video_info['duration'] // 60)
secs = int(video_info['duration'] % 60)
st.metric("Duration", f"{mins}:{secs:02d}")
if video_info['width'] and video_info['height']:
st.metric("Resolution", f"{video_info['width']}x{video_info['height']}")
if video_info['fps']:
st.metric("Frame Rate", f"{video_info['fps']} fps")
with col_b:
if video_info['video_codec']:
st.metric("Video Codec", video_info['video_codec'].upper())
if video_info['bitrate']:
st.metric("Bitrate", f"{video_info['bitrate']} kbps")
st.metric("Has Audio", "Yes" if video_info['has_audio'] else "No")
# Get compression suggestion
suggestion = get_video_compression_suggestion(video_info)
# Show suggestion
st.markdown("---")
st.markdown("**π‘ Recommended Compression**")
method_names = {
'h264': 'H.264/AVC (Universal)',
'av1': 'AV1 (Best Compression)'
}
rec_method = suggestion['method']
rec_crf = suggestion.get('crf', 23)
if suggestion.get('warning'):
st.warning(f"β οΈ {suggestion['warning']}")
st.success(f"β¨ **{method_names.get(rec_method, rec_method)}** - {suggestion['reason']}")
# Method selection
st.markdown("**π§ Compression Method**")
video_method = st.radio(
"Select Method",
options=["H.264/AVC (Fast & Compatible)", "AV1 (Better Compression)"],
horizontal=True,
index=0 if rec_method == 'h264' else 1,
help="H.264: Fast encoding, universal playback | AV1: Better compression, slower encoding"
)
# Map selection to method code
video_method_code = 'h264' if 'H.264' in video_method else 'av1'
if video_method_code == 'h264':
st.markdown("---")
st.markdown("**π₯ H.264/AVC** (Advanced Video Coding)")
st.caption("β Universal compatibility")
st.caption("β Fast encoding")
st.caption("β Hardware acceleration support")
# Quality selection
quality_preset = st.select_slider(
"Video Quality",
options=["Low (CRF 28)", "Medium (CRF 23)", "High (CRF 18)", "Very High (CRF 14)", "Near Lossless (CRF 10)"],
value="Medium (CRF 23)",
help="Lower CRF = better quality, larger file"
)
crf_map = {
"Low (CRF 28)": 28,
"Medium (CRF 23)": 23,
"High (CRF 18)": 18,
"Very High (CRF 14)": 14,
"Near Lossless (CRF 10)": 10
}
video_crf = crf_map[quality_preset]
# Preset selection
speed_preset = st.select_slider(
"Encoding Speed",
options=["ultrafast", "superfast", "veryfast", "faster", "fast", "medium", "slow", "slower", "veryslow"],
value="medium",
help="Slower = better compression at same quality"
)
video_preset = speed_preset
else: # av1
st.markdown("---")
st.markdown("**π― AV1** (AOMedia Video 1)")
st.caption("β 30-50% better compression than H.264")
st.caption("β Royalty-free")
st.caption("β οΈ Slower encoding")
# Quality selection for AV1
quality_preset = st.select_slider(
"Video Quality",
options=["Low (CRF 40)", "Medium (CRF 30)", "High (CRF 22)", "Very High (CRF 15)"],
value="Medium (CRF 30)",
help="Lower CRF = better quality, larger file"
)
crf_map = {
"Low (CRF 40)": 40,
"Medium (CRF 30)": 30,
"High (CRF 22)": 22,
"Very High (CRF 15)": 15
}
video_crf = crf_map[quality_preset]
# Preset selection for AV1
speed_preset = st.select_slider(
"Encoding Speed",
options=["fast", "medium", "slow"],
value="medium",
help="Slower = better compression at same quality"
)
video_preset = speed_preset
st.warning("β οΈ AV1 encoding is significantly slower than H.264. For large videos, consider using H.264.")
st.markdown("##### 𧬠DNA Mapping")
st.code("A=00, T=01, G=10, C=11 (2 bits per nucleotide)", language=None)
# Confirmation and encode button
st.markdown("---")
st.markdown("##### β
Confirm & Encode")
with st.expander("π Parameter Summary", expanded=True):
st.write(f"**File:** {filename}")
st.write(f"**Size:** {len(file_data):,} bytes")
st.write(f"**Type:** {file_type.title()}")
# Show specific compression type
if compression_option == "None":
compression_display = "None"
else:
# Determine specific compression based on file type
if file_type == 'text' or file_type == 'binary':
compression_display = f"Brotli (Quality {brotli_quality})"
elif file_type == 'image':
compression_display = f"WebP (Quality {webp_quality})"
elif file_type == 'pdf':
if pdf_method_code == 'pdf_opt':
compression_display = "PDF Object Optimization (Lossless)"
else:
compression_display = f"PDF Image Downsampling ({pdf_image_dpi} DPI)"
elif file_type == 'audio':
if audio_method_code == 'flac':
compression_display = "FLAC (Lossless)"
elif audio_method_code == 'aac':
compression_display = f"AAC ({audio_bitrate} kbps)"
else:
compression_display = f"MP3 ({audio_bitrate} kbps)"
elif file_type == 'video':
if video_method_code == 'h264':
compression_display = f"H.264 (CRF {video_crf}, {video_preset})"
else:
compression_display = f"AV1 (CRF {video_crf}, {video_preset})"
else:
compression_display = "Brotli (Default)"
st.write(f"**Compression:** {compression_display}")
st.write("**Metadata:** Embedded in DNA sequence")
if st.button("π Start Encoding", type="primary", use_container_width=True):
with st.spinner("Encoding in progress..."):
start_time = time.time()
# Apply compression if selected
if compression_option == "Data-Type-Specific":
compressed_data, comp_type = compress_data(
file_data, file_type, 'auto',
brotli_quality=brotli_quality,
webp_quality=webp_quality,
pdf_image_dpi=pdf_image_dpi,
pdf_image_quality=pdf_image_quality,
pdf_method=pdf_method_code,
audio_method=audio_method_code,
audio_bitrate=audio_bitrate,
video_method=video_method_code,
video_crf=video_crf,
video_preset=video_preset
)
compressed = comp_type != 'none'
else:
compressed_data = file_data
comp_type = 'none'
compressed = False
# Encode to DNA
dna_sequence = encode_to_dna(
compressed_data,
compressed=compressed,
compression_type=comp_type,
original_extension=file_ext
)
encoding_time = time.time() - start_time
# Store in session state
st.session_state.encoded_dna = dna_sequence
st.session_state.encoded_metadata = {
'filename': filename,
'original_size': len(file_data),
'compressed_size': len(compressed_data),
'compression_type': comp_type,
'dna_length': len(dna_sequence),
'encoding_time': encoding_time,
'file_type': file_type,
'extension': file_ext
}
st.success("β
Encoding completed successfully!")
with col2:
st.subheader("π€ Output")
if st.session_state.encoded_dna:
dna = st.session_state.encoded_dna
meta = st.session_state.encoded_metadata
# Result preview
st.markdown("##### π¬ Result Preview")
preview_length = min(500, len(dna))
preview_text = dna[:preview_length]
if len(dna) > preview_length:
preview_text += f"\n... ({len(dna) - preview_length:,} more nucleotides)"
st.text_area(
"DNA Sequence Preview",
value=preview_text,
height=200,
disabled=True
)
# Encoding details
st.markdown("##### π Encoding Details")
detail_col1, detail_col2 = st.columns(2)
with detail_col1:
st.metric("DNA Length", f"{meta['dna_length']:,} nt")
st.metric("Original Size", f"{meta['original_size']:,} bytes")
if meta['compression_type'] != 'none':
st.metric("Compressed Size", f"{meta['compressed_size']:,} bytes")
with detail_col2:
density = calculate_encoding_density(meta['original_size'], meta['dna_length'])
st.metric("Encoding Density", f"{density:.4f} bits/nt")
st.metric("Encoding Time", f"{meta['encoding_time']:.3f} s")
st.metric("Compression", meta['compression_type'].upper())
if meta['compression_type'] != 'none':
ratio = meta['original_size'] / meta['compressed_size']
st.metric("Compression Ratio", f"{ratio:.2f}x")
else:
# Explain why compression is "none"
st.markdown("---")
st.markdown("##### βΉοΈ Compression Status")
file_type = meta.get('file_type', 'binary')
# Check if compression was disabled by user choice
if meta['original_size'] == meta['compressed_size']:
explanations = []
if file_type in ('text', 'binary'):
explanations.append("**Brotli compression** was applied but the compressed data was larger than or equal to the original.")
explanations.append("This typically happens with:")
explanations.append("- Already compressed files (ZIP, RAR, etc.)")
explanations.append("- Small files with little redundancy")
explanations.append("- Random or encrypted data")
elif file_type == 'image':
explanations.append("**WebP compression** was applied but the compressed image was larger than the original.")
explanations.append("This can happen with:")
explanations.append("- Already highly compressed images (JPEG at low quality)")
explanations.append("- Small images with few pixels")
explanations.append("- Images with high entropy/noise")
elif file_type == 'audio':
explanations.append("**Audio compression** was applied but did not reduce file size.")
explanations.append("This typically happens with:")
explanations.append("- Already compressed audio (MP3, AAC)")
explanations.append("- Very short audio clips")
elif file_type == 'video':
explanations.append("**Video compression** was applied but did not reduce file size.")
explanations.append("This typically happens with:")
explanations.append("- Already highly compressed video")
explanations.append("- Very short video clips")
elif file_type == 'pdf':
explanations.append("**PDF optimization** was applied but did not reduce file size.")
explanations.append("This typically happens with:")
explanations.append("- Already optimized PDFs")
explanations.append("- PDFs without embedded images")
for exp in explanations:
st.caption(exp)
st.info("π‘ **Result:** Data stored uncompressed at the baseline 2.0 bits/nucleotide density.")
# Download button
st.markdown("##### πΎ Download")
st.download_button(
label="π₯ Download DNA Sequence (.txt)",
data=dna,
file_name=f"{os.path.splitext(meta['filename'])[0]}_dna.txt",
mime="text/plain",
use_container_width=True
)
else:
st.info("π Upload a file and click 'Start Encoding' to see results here.")
def randomization_mode():
"""Randomization mode: Apply chaos map to DNA sequence."""
st.header("π Randomization Mode")
st.markdown("Apply chaos map to randomise and secure DNA sequence.")
col1, col2 = st.columns([1, 1])
with col1:
st.subheader("π₯ Input")
# Data source selection
input_source = st.radio(
"DNA Sequence Source",
options=["From Encode Mode", "Upload DNA File"],
horizontal=True
)
dna_sequence = None
if input_source == "From Encode Mode":
if st.session_state.encoded_dna:
dna_sequence = st.session_state.encoded_dna
st.success(f"β
Loaded DNA sequence ({len(dna_sequence):,} nt) from Encode mode")
else:
st.warning("β οΈ No DNA sequence available from Encode mode. Please encode a file first.")
else:
uploaded_dna = st.file_uploader(
"Upload DNA sequence file (.txt)",
type=['txt'],
key="random_upload"
)
if uploaded_dna:
dna_sequence = uploaded_dna.read().decode('utf-8').strip()
dna_sequence = ''.join(c for c in dna_sequence.upper() if c in 'ATGC')
if validate_dna_sequence(dna_sequence):
st.success(f"β
Loaded valid DNA sequence ({len(dna_sequence):,} nt)")
else:
st.error("β Invalid DNA sequence. Only A, T, G, C characters allowed.")
dna_sequence = None
if dna_sequence:
# Show original characteristics
st.markdown("##### π Original DNA Characteristics")
orig_chars = calculate_dna_characteristics(dna_sequence)
char_col1, char_col2 = st.columns(2)
with char_col1:
st.metric("Length", f"{orig_chars['length']:,} nt")
st.metric("Max Homopolymer", f"{orig_chars['max_homopolymer']} nt")
with char_col2:
st.metric("GC Ratio", f"{orig_chars['gc_ratio']:.4f}")
st.metric("Shannon Entropy", f"{orig_chars['shannon_entropy']:.4f}")
st.markdown("---")
# Randomization options
st.markdown("##### βοΈ Randomization Options")
randomization_option = st.radio(
"Randomization",
options=["None", "Apply Randomization"],
horizontal=True
)
forward_primer = ""
reverse_primer = ""
selected_system = ChaosSystem.HENON # Default
if randomization_option == "Apply Randomization":
st.info("π **Chaos Map Encryption** uses primer sequences as keys.")
# Chaos system selection
chaos_options = {
"Logistic Map (1D - Simple)": ChaosSystem.LOGISTIC,
"HΓ©non Map (2D - Medium)": ChaosSystem.HENON,
"Lorenz System (3D - Complex)": ChaosSystem.LORENZ
}
selected_system_name = st.selectbox(
"Chaos System",
options=list(chaos_options.keys()),
index=1, # Default to HΓ©non
help="Choose chaotic system complexity: Simple β Medium β Complex"
)
selected_system = chaos_options[selected_system_name]
# Show system info
system_info = get_chaos_system_info(selected_system)
with st.expander("βΉοΈ System Details", expanded=False):
st.markdown(f"**{system_info['name']}** ({system_info['dimensions']}D)")
st.markdown(f"*Complexity:* {system_info['complexity']}")
st.markdown(f"*Equation:* `{system_info['equation']}`")
st.markdown(f"*Description:* {system_info['description']}")
st.markdown("---")
forward_primer = st.text_input(
"Forward Primer (Key 1)",
value="ACACGACGCTCTTCCGATCT",
help="DNA sequence used as part of the encryption key",
max_chars=50
)
reverse_primer = st.text_input(
"Reverse Primer (Key 2)",
value="AGATCGGAAGAGCACACGTCT",
help="DNA sequence used as part of the encryption key",
max_chars=50
)
if forward_primer and reverse_primer:
if not all(c in 'ATGCatgc' for c in forward_primer):
st.error("β Forward primer contains invalid characters")
elif not all(c in 'ATGCatgc' for c in reverse_primer):
st.error("β Reverse primer contains invalid characters")
# Apply randomization
st.markdown("---")
if st.button("π Apply Randomization", type="primary", use_container_width=True):
if randomization_option == "None":
st.session_state.randomized_dna = dna_sequence
st.session_state.chaos_system = None
st.success("β
No randomization applied. DNA sequence passed through.")
else:
if not forward_primer or not reverse_primer:
st.error("β Please enter both primer sequences")
else:
system_info = get_chaos_system_info(selected_system)
with st.spinner(f"Applying {system_info['name']} scrambling..."):
randomized = randomize_dna(
dna_sequence,
forward_primer,
reverse_primer,
system=selected_system
)
st.session_state.randomized_dna = randomized
# Store primers and system for decode reference
st.session_state.randomization_primers = {
'forward': forward_primer.upper(),
'reverse': reverse_primer.upper()
}
st.session_state.chaos_system = selected_system
st.success(f"β
Randomization completed!")
with col2:
st.subheader("π€ Output")
if st.session_state.randomized_dna:
randomized_dna = st.session_state.randomized_dna
# Preview
st.markdown("##### π¬ Randomized DNA Preview")
preview_length = min(500, len(randomized_dna))
preview_text = randomized_dna[:preview_length]
if len(randomized_dna) > preview_length:
preview_text += f"\n... ({len(randomized_dna) - preview_length:,} more nucleotides)"
st.text_area(
"Randomized DNA Sequence",
value=preview_text,
height=200,
disabled=True
)
# Characteristics after randomization
st.markdown("##### π Randomized DNA Characteristics")
rand_chars = calculate_dna_characteristics(randomized_dna)
char_col1, char_col2 = st.columns(2)
with char_col1:
st.metric("Length", f"{rand_chars['length']:,} nt")
st.metric("Max Homopolymer", f"{rand_chars['max_homopolymer']} nt")
with char_col2:
st.metric("GC Ratio", f"{rand_chars['gc_ratio']:.4f}")
st.metric("Shannon Entropy", f"{rand_chars['shannon_entropy']:.4f}")
# Download
st.markdown("##### πΎ Download")
st.download_button(
label="π₯ Download Randomized DNA (.txt)",
data=randomized_dna,
file_name="randomized_dna.txt",
mime="text/plain",
use_container_width=True
)
else:
st.info("π Load a DNA sequence and apply randomization to see results here.")
def decode_mode():
"""Decode mode: Convert DNA sequence back to original file."""
st.header("π₯ Decode Mode")
st.markdown("Decode DNA sequences back to their original file format.")
col1, col2 = st.columns([1, 1])
with col1:
st.subheader("π₯ Input")
# Data source selection