Repository navigation
Expand file tree
/
Copy pathmain-gui.py
More file actions
1113 lines (946 loc) Β· 46 KB
/
Copy pathmain-gui.py
File metadata and controls
1113 lines (946 loc) Β· 46 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 os
import json
import base64
import tempfile
import random
import zipfile
import io
from datetime import timedelta, datetime
from dotenv import load_dotenv
from google.cloud import storage
import streamlit as st
import pandas as pd
from PIL import Image
import mimetypes
from collections import Counter
import plotly.express as px
import plotly.graph_objects as go
# 1. Load .env
load_dotenv(dotenv_path=".env")
# 2. Get env vars
service_account_b64 = os.getenv("GOOGLE_APPLICATION_CREDENTIALS_JSON_BASE64")
photo_bucket = os.getenv("PHOTO_BUCKET") if os.getenv("PHOTO_BUCKET") else os.getenv("PHOTO_STORAGE_BUCKET")
# 3. Decode base64 JSON and write to temp file
service_account_info = json.loads(base64.b64decode(service_account_b64))
with tempfile.NamedTemporaryFile(delete=False, suffix=".json") as tmp:
tmp.write(json.dumps(service_account_info).encode("utf-8"))
service_account_path = tmp.name
# 4. Auth with service account file
client = storage.Client.from_service_account_json(service_account_path)
bucket = client.bucket(photo_bucket)
# 5. Get all blobs sorted by time (latest first)
blobs = sorted(bucket.list_blobs(), key=lambda b: b.updated, reverse=True)
# Helper functions
def get_file_extension(filename):
return os.path.splitext(filename)[1].lower()
def get_detailed_file_type(filename):
"""Get detailed file type with category and MIME type"""
ext = get_file_extension(filename)
# Enhanced file type detection with more extensions
image_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.tiff', '.svg', '.ico', '.raw', '.heic', '.heif', '.psd', '.ai', '.eps'}
video_extensions = {'.mp4', '.avi', '.mov', '.wmv', '.flv', '.webm', '.mkv', '.m4v', '.3gp', '.ogv', '.mpg', '.mpeg', '.m2v', '.asf', '.rm', '.rmvb'}
audio_extensions = {'.mp3', '.wav', '.flac', '.aac', '.ogg', '.wma', '.m4a', '.opus', '.amr', '.au', '.ra', '.mid', '.midi'}
document_extensions = {'.pdf', '.doc', '.docx', '.txt', '.rtf', '.odt', '.xls', '.xlsx', '.ppt', '.pptx', '.csv', '.xml', '.json', '.yaml', '.yml', '.md', '.rst'}
archive_extensions = {'.zip', '.rar', '.7z', '.tar', '.gz', '.bz2', '.xz', '.lz', '.lzma', '.cab', '.iso', '.dmg'}
code_extensions = {'.py', '.js', '.html', '.css', '.java', '.cpp', '.c', '.php', '.rb', '.go', '.rs', '.swift', '.kt', '.scala', '.ts', '.tsx', '.jsx', '.vue', '.svelte'}
database_extensions = {'.db', '.sqlite', '.sqlite3', '.mdb', '.accdb', '.sql'}
executable_extensions = {'.exe', '.msi', '.deb', '.rpm', '.dmg', '.pkg', '.app', '.bin', '.run'}
# Try to get MIME type
mime_type, _ = mimetypes.guess_type(filename)
if ext in image_extensions:
return f"πΌοΈ Image ({ext[1:].upper()})" + (f" - {mime_type}" if mime_type else "")
elif ext in video_extensions:
return f"π₯ Video ({ext[1:].upper()})" + (f" - {mime_type}" if mime_type else "")
elif ext in audio_extensions:
return f"π΅ Audio ({ext[1:].upper()})" + (f" - {mime_type}" if mime_type else "")
elif ext in document_extensions:
return f"π Document ({ext[1:].upper()})" + (f" - {mime_type}" if mime_type else "")
elif ext in archive_extensions:
return f"π¦ Archive ({ext[1:].upper()})" + (f" - {mime_type}" if mime_type else "")
elif ext in code_extensions:
return f"π» Code ({ext[1:].upper()})" + (f" - {mime_type}" if mime_type else "")
elif ext in database_extensions:
return f"ποΈ Database ({ext[1:].upper()})" + (f" - {mime_type}" if mime_type else "")
elif ext in executable_extensions:
return f"βοΈ Executable ({ext[1:].upper()})" + (f" - {mime_type}" if mime_type else "")
elif ext:
return f"π Other ({ext[1:].upper()})" + (f" - {mime_type}" if mime_type else "")
else:
return "β Unknown Type"
def is_image_file(filename):
image_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.tiff', '.svg', '.ico', '.raw'}
return get_file_extension(filename) in image_extensions
def is_video_file(filename):
video_extensions = {'.mp4', '.avi', '.mov', '.wmv', '.flv', '.webm', '.mkv', '.m4v', '.3gp', '.ogv'}
return get_file_extension(filename) in video_extensions
def get_folder_path(filename):
return '/'.join(filename.split('/')[:-1]) if '/' in filename else ''
def format_datetime(dt):
"""Format datetime with detailed information"""
if not dt:
return "Not Available"
# Get current time for comparison
now = datetime.now(dt.tzinfo) if dt.tzinfo else datetime.now()
diff = now - dt
# Format based on how recent it is
if diff.days == 0:
if diff.seconds < 60:
return f"Just now ({dt.strftime('%H:%M:%S')})"
elif diff.seconds < 3600:
minutes = diff.seconds // 60
return f"{minutes} minute{'s' if minutes != 1 else ''} ago ({dt.strftime('%H:%M:%S')})"
else:
hours = diff.seconds // 3600
return f"{hours} hour{'s' if hours != 1 else ''} ago ({dt.strftime('%H:%M:%S')})"
elif diff.days == 1:
return f"Yesterday ({dt.strftime('%H:%M:%S')})"
elif diff.days < 7:
return f"{diff.days} days ago ({dt.strftime('%a %H:%M:%S')})"
elif diff.days < 30:
weeks = diff.days // 7
return f"{weeks} week{'s' if weeks != 1 else ''} ago ({dt.strftime('%b %d, %H:%M')})"
elif diff.days < 365:
months = diff.days // 30
return f"{months} month{'s' if months != 1 else ''} ago ({dt.strftime('%b %d, %Y')})"
else:
years = diff.days // 365
return f"{years} year{'s' if years != 1 else ''} ago ({dt.strftime('%b %d, %Y')})"
def get_file_age_category(dt):
"""Get age category for files"""
if not dt:
return "Unknown"
now = datetime.now(dt.tzinfo) if dt.tzinfo else datetime.now()
diff = now - dt
if diff.days == 0:
return "Today"
elif diff.days < 7:
return "This Week"
elif diff.days < 30:
return "This Month"
elif diff.days < 90:
return "Last 3 Months"
elif diff.days < 365:
return "This Year"
else:
return "Older"
def format_file_size(size_bytes):
"""Format file size in human readable format"""
if size_bytes is None:
return "Unknown"
if size_bytes == 0:
return "0 B"
size_names = ["B", "KB", "MB", "GB", "TB"]
i = 0
while size_bytes >= 1024 and i < len(size_names) - 1:
size_bytes /= 1024.0
i += 1
return f"{size_bytes:.2f} {size_names[i]}"
def format_datetime(dt):
"""Format datetime with detailed information"""
if dt is None:
return "Unknown"
if isinstance(dt, str):
return dt
# Calculate time ago
now = datetime.now(dt.tzinfo) if dt.tzinfo else datetime.now()
time_diff = now - dt
if time_diff.days > 0:
time_ago = f"{time_diff.days} day{'s' if time_diff.days != 1 else ''} ago"
elif time_diff.seconds > 3600:
hours = time_diff.seconds // 3600
time_ago = f"{hours} hour{'s' if hours != 1 else ''} ago"
elif time_diff.seconds > 60:
minutes = time_diff.seconds // 60
time_ago = f"{minutes} minute{'s' if minutes != 1 else ''} ago"
else:
time_ago = "Just now"
return f"{dt.strftime('%Y-%m-%d %H:%M:%S')} ({time_ago})"
def get_content_type_detailed(filename):
"""Get detailed content type"""
content_type, _ = mimetypes.guess_type(filename)
if content_type:
return content_type
else:
return get_detailed_file_type(filename)
def create_file_dataframe(blobs):
data = []
for blob in blobs:
data.append({
'Name': blob.name,
'Size (bytes)': blob.size,
'Size (Formatted)': format_file_size(blob.size),
'Size (MB)': round(blob.size / (1024*1024), 2) if blob.size else 0,
'Content Type': blob.content_type or get_content_type_detailed(blob.name),
'File Type': get_detailed_file_type(blob.name),
'Created': format_datetime(blob.time_created),
'Updated': format_datetime(blob.updated),
'Folder': get_folder_path(blob.name) or 'Root',
'Extension': get_file_extension(blob.name) or 'No Extension',
'Is Image': is_image_file(blob.name),
'Is Video': is_video_file(blob.name),
'MD5 Hash': blob.md5_hash or 'Unknown',
'CRC32C': blob.crc32c or 'Unknown'
})
return pd.DataFrame(data)
def generate_signed_urls(blobs, expiration_hours=1):
urls = []
for blob in blobs:
try:
url = blob.generate_signed_url(expiration=timedelta(hours=expiration_hours), method="GET")
urls.append({
'filename': blob.name,
'signed_url': url,
'expires_in_hours': expiration_hours
})
except Exception as e:
urls.append({
'filename': blob.name,
'signed_url': f"Error: {str(e)}",
'expires_in_hours': 0
})
return urls
def create_zip_file(selected_blobs, bucket):
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
for blob_name in selected_blobs:
blob = bucket.blob(blob_name)
if blob.exists():
file_data = blob.download_as_bytes()
zip_file.writestr(blob_name, file_data)
zip_buffer.seek(0)
return zip_buffer
def create_folder(bucket, folder_path):
"""Create a folder by uploading an empty file with folder path"""
if not folder_path.endswith('/'):
folder_path += '/'
# Create a placeholder file to represent the folder
placeholder_path = folder_path + '.folder_placeholder'
blob = bucket.blob(placeholder_path)
blob.upload_from_string('', content_type='text/plain')
return True
def rename_file_or_folder(bucket, old_path, new_path):
"""Rename a file or folder"""
try:
# If it's a folder, we need to rename all files in that folder
if old_path.endswith('/'):
# Get all blobs with the old folder prefix
blobs_to_rename = list(bucket.list_blobs(prefix=old_path))
for blob in blobs_to_rename:
# Calculate new path
relative_path = blob.name[len(old_path):]
new_blob_path = new_path + relative_path
# Copy to new location (handles binary files properly)
bucket.copy_blob(blob, bucket, new_blob_path)
# Delete old blob
blob.delete()
return True
else:
# Single file rename
blob = bucket.blob(old_path)
if blob.exists():
# Use copy_blob to handle binary files properly
bucket.copy_blob(blob, bucket, new_path)
blob.delete()
return True
return False
except Exception as e:
st.error(f"Error renaming: {str(e)}")
return False
def delete_file_or_folder(bucket, path):
"""Delete a file or folder"""
try:
if path.endswith('/'):
# Delete all files in folder
blobs_to_delete = list(bucket.list_blobs(prefix=path))
for blob in blobs_to_delete:
blob.delete()
else:
# Delete single file
blob = bucket.blob(path)
if blob.exists():
blob.delete()
return True
except Exception as e:
st.error(f"Error deleting: {str(e)}")
return False
def get_all_folders(blobs):
"""Get all unique folders from blob list"""
folders = set()
for blob in blobs:
folder_path = get_folder_path(blob.name)
if folder_path:
folders.add(folder_path)
return sorted(list(folders))
def is_binary_file(filename):
"""Check if a file is likely to be binary based on extension"""
binary_extensions = {
'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.tiff', '.svg', '.ico', '.raw',
'.mp4', '.avi', '.mov', '.wmv', '.flv', '.webm', '.mkv', '.m4v', '.3gp', '.ogv',
'.mp3', '.wav', '.flac', '.aac', '.ogg', '.wma', '.m4a', '.opus', '.amr',
'.zip', '.rar', '.7z', '.tar', '.gz', '.bz2', '.xz', '.lz', '.lzma', '.cab', '.iso', '.dmg',
'.exe', '.msi', '.deb', '.rpm', '.pkg', '.app', '.bin', '.run',
'.db', '.sqlite', '.sqlite3', '.mdb', '.accdb',
'.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx'
}
return get_file_extension(filename) in binary_extensions
# -------- Streamlit UI --------
st.set_page_config(page_title="Google Cloud Storage Manager", layout="centered")
# Header with bucket info
st.markdown("""
<div style="text-align: center; padding: 1rem; background-color: #4B0082; border-radius: 10px; margin-bottom: 2rem;">
<h1 style="color: white; margin: 0; position: sticky; top: 10px;">ποΈ Google Cloud Storage File Manager</h1>
<p style="color: white; margin: 0.5rem 0 0 0; font-size: 1.1rem;">Professional File Management & Analytics</p>
</div>
""", unsafe_allow_html=True)
# Hide default Streamlit menu and footer
st.markdown("""
<style>
#MainMenu {visibility: hidden;}
footer {visibility: hidden;}
</style>
""", unsafe_allow_html=True)
# Simple radio button sidebar for menu selection
menu = [
"βΉοΈ Bucket Info & Analytics",
"π Dashboard",
"π Folder Management",
"π€ Advanced Upload",
"π₯ Bulk Download",
"π Advanced Search & Preview",
"π Export Links & Metadata",
"π Simple Search",
"π File Details",
]
selected_menu = st.sidebar.radio("Menu", menu, index=0)
if selected_menu == "βΉοΈ Bucket Info & Analytics":
st.header("βΉοΈ Bucket Information & Analytics")
# Prepare data for the table
info_data = [
["Bucket Name", bucket.name],
["Project", client.project],
["Total Files", len(blobs)],
["Total Size", format_file_size(sum(blob.size for blob in blobs if blob.size))],
["Average File Size", format_file_size((sum(blob.size for blob in blobs if blob.size) // len(blobs)) if blobs else 0)],
["Largest File", format_file_size(max((blob.size for blob in blobs if blob.size), default=0))]
]
info_df = pd.DataFrame(info_data, columns=["Property", "Value"])
# Use Streamlit's table with lines (styling for lines)
st.table(info_df.style.set_properties(**{
'border': '1px solid #888',
'border-collapse': 'collapse'
}))
# File type breakdown with chart
st.subheader("π File Type Distribution")
file_types = [get_detailed_file_type(blob.name) for blob in blobs]
type_counts = Counter(file_types)
col1, col2 = st.columns([2, 1])
with col1:
# Create pie chart
fig = px.pie(
values=list(type_counts.values()),
names=list(type_counts.keys()),
title="File Types Distribution"
)
st.plotly_chart(fig, use_container_width=True)
with col2:
st.write("**File Type Counts:**")
# Prepare the file type counts as a list of strings
file_type_lines = [
f"β’ {file_type}: {count}"
for file_type, count in sorted(type_counts.items(), key=lambda x: x[1], reverse=True)
]
# Display in a scrollable div with fixed height (approx 400px to match chart)
file_type_html = (
"<div style='overflow-y:auto; height:400px; border:1px solid rgba(0, 0, 0, 0.1); padding:8px;'>"
+ "<br>".join(file_type_lines)
+ "</div>"
)
st.markdown(file_type_html, unsafe_allow_html=True)
# Folder structure
st.subheader("π Folder Structure")
folders = {}
for blob in blobs:
folder = get_folder_path(blob.name) or 'Root'
if folder not in folders:
folders[folder] = 0
folders[folder] += 1
col1, col2 = st.columns([2, 1])
with col1:
# Create bar chart for folders
if len(folders) > 1:
fig = px.bar(
x=list(folders.keys()),
y=list(folders.values()),
title="Files per Folder",
labels={'x': 'Folder', 'y': 'File Count'}
)
fig.update_layout(xaxis_tickangle=45)
st.plotly_chart(fig, use_container_width=True)
with col2:
st.write("**Folder Contents:**")
# Set a fixed height for the scrollable area to match the chart height (approx 400px)
folder_contents = [
f"β’ {folder}: {count} files"
for folder, count in sorted(folders.items(), key=lambda x: x[1], reverse=True)
]
# Use markdown with a scrollable div
folder_list_html = (
"<div style='overflow-y:auto; height:400px; border:1px solid rgba(0, 0, 0, 0.1); padding:8px;'>"
+ "<br>".join(folder_contents)
+ "</div>"
)
st.markdown(folder_list_html, unsafe_allow_html=True)
# Recent activity
st.subheader("π Recent Activity")
recent_files = blobs[:10]
recent_data = []
for blob in recent_files:
recent_data.append({
'File': blob.name,
'Size': format_file_size(blob.size),
'Type': get_detailed_file_type(blob.name),
'Updated': format_datetime(blob.updated)
})
if recent_data:
recent_df = pd.DataFrame(recent_data)
st.dataframe(recent_df, use_container_width=True)
# Storage trends
st.subheader("π Storage Trends")
if len(blobs) > 1:
# Group by month for trend analysis
monthly_data = {}
for blob in blobs:
if blob.updated:
month_key = blob.updated.strftime('%Y-%m')
if month_key not in monthly_data:
monthly_data[month_key] = {'count': 0, 'size': 0}
monthly_data[month_key]['count'] += 1
monthly_data[month_key]['size'] += blob.size or 0
if monthly_data:
months = sorted(monthly_data.keys())
counts = [monthly_data[month]['count'] for month in months]
sizes = [monthly_data[month]['size'] / (1024*1024) for month in months] # Convert to MB
col1, col2 = st.columns(2)
with col1:
fig = px.line(x=months, y=counts, title="Files Added Over Time")
st.plotly_chart(fig, use_container_width=True)
with col2:
fig = px.line(x=months, y=sizes, title="Storage Used Over Time (MB)")
st.plotly_chart(fig, use_container_width=True)
elif selected_menu == "π Folder Management":
st.header("π Folder Management")
# Get all folders
folders = set()
for blob in blobs:
folder_path = get_folder_path(blob.name)
if folder_path:
folders.add(folder_path)
folders = sorted(list(folders))
col1, col2 = st.columns([2, 1])
with col1:
st.subheader("π Existing Folders")
if folders:
selected_folder = st.selectbox("Select a folder:", ["Root (/)"] + folders)
if selected_folder == "Root (/)":
folder_path = ""
else:
folder_path = selected_folder
# Show files in selected folder
folder_files = [blob for blob in blobs if get_folder_path(blob.name) == folder_path]
st.write(f"Files in {selected_folder}: {len(folder_files)}")
if folder_files:
for blob in folder_files[:20]: # Show first 20 files
col_a, col_b, col_c = st.columns([3, 1, 1])
with col_a:
st.write(f"π {blob.name}")
with col_b:
if st.button("π Rename", key=f"rename_{blob.name}"):
st.session_state.rename_file = blob.name
with col_c:
if st.button("ποΈ Delete", key=f"delete_{blob.name}"):
st.session_state.delete_file = blob.name
else:
st.info("No folders found. All files are in the root directory.")
with col2:
st.subheader("π οΈ Folder Actions")
# Create new folder
st.write("**Create New Folder:**")
new_folder_name = st.text_input("Folder name:", placeholder="folder/subfolder")
if st.button("π Create Folder") and new_folder_name:
# Create a placeholder file to create the folder
placeholder_path = f"{new_folder_name}/.folder_placeholder"
blob = bucket.blob(placeholder_path)
blob.upload_from_string("")
st.success(f"β
Created folder: {new_folder_name}")
st.rerun()
# Rename file/folder
if hasattr(st.session_state, 'rename_file'):
st.write("**Rename File:**")
new_name = st.text_input("New name:", value=st.session_state.rename_file)
if st.button("β
Confirm Rename"):
try:
old_blob = bucket.blob(st.session_state.rename_file)
new_blob = bucket.blob(new_name)
# Use copy_blob instead of download/upload to handle binary files
bucket.copy_blob(old_blob, bucket, new_name)
old_blob.delete()
st.success(f"β
Renamed to: {new_name}")
del st.session_state.rename_file
st.rerun()
except Exception as e:
st.error(f"β Rename failed: {str(e)}")
del st.session_state.rename_file
# Delete file
if hasattr(st.session_state, 'delete_file'):
st.write("**Delete File:**")
st.warning(f"Are you sure you want to delete: {st.session_state.delete_file}?")
if st.button("ποΈ Confirm Delete"):
blob = bucket.blob(st.session_state.delete_file)
blob.delete()
st.success(f"β
Deleted: {st.session_state.delete_file}")
del st.session_state.delete_file
st.rerun()
elif selected_menu == "π Dashboard":
st.header("π Dashboard & Table View")
# Dashboard metrics
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Total Files", len(blobs))
with col2:
total_size = sum(blob.size for blob in blobs if blob.size)
st.metric("Total Size (MB)", f"{total_size / (1024*1024):.1f}")
with col3:
image_count = sum(1 for blob in blobs if is_image_file(blob.name))
st.metric("Images", image_count)
with col4:
video_count = sum(1 for blob in blobs if is_video_file(blob.name))
st.metric("Videos", video_count)
# Filters
st.subheader("π Filters")
col1, col2, col3 = st.columns(3)
with col1:
folder_filter = st.selectbox("Filter by Folder", ["All"] + list(set(get_folder_path(blob.name) for blob in blobs if get_folder_path(blob.name))))
with col2:
extension_filter = st.selectbox("Filter by Extension", ["All"] + list(set(get_file_extension(blob.name) for blob in blobs if get_file_extension(blob.name))))
with col3:
file_type_filter = st.selectbox("Filter by Type", ["All", "Images Only", "Videos Only", "Other Files"])
# Apply filters
filtered_blobs = blobs
if folder_filter != "All":
filtered_blobs = [b for b in filtered_blobs if get_folder_path(b.name) == folder_filter]
if extension_filter != "All":
filtered_blobs = [b for b in filtered_blobs if get_file_extension(b.name) == extension_filter]
if file_type_filter == "Images Only":
filtered_blobs = [b for b in filtered_blobs if is_image_file(b.name)]
elif file_type_filter == "Videos Only":
filtered_blobs = [b for b in filtered_blobs if is_video_file(b.name)]
elif file_type_filter == "Other Files":
filtered_blobs = [b for b in filtered_blobs if not is_image_file(b.name) and not is_video_file(b.name)]
st.write(f"Showing {len(filtered_blobs)} files")
# Create and display table
if filtered_blobs:
df = create_file_dataframe(filtered_blobs)
# Display options
col1, col2 = st.columns([3, 1])
with col1:
st.dataframe(df, use_container_width=True, height=400)
with col2:
st.subheader("Export Options")
if st.button("π Export CSV"):
csv = df.to_csv(index=False)
st.download_button("Download CSV", csv, "files_data.csv", "text/csv")
if st.button("π Export JSON"):
json_data = df.to_json(orient='records', indent=2)
st.download_button("Download JSON", json_data, "files_data.json", "application/json")
elif selected_menu == "π Advanced Search & Preview":
st.header("π Advanced Search & Preview")
# Search options
col1, col2 = st.columns([2, 1])
with col1:
search_pattern = st.text_input("π Search pattern (filename contains)", placeholder="Enter text to search in filenames")
with col2:
search_type = st.selectbox("Search Type", ["Contains", "Starts with", "Ends with", "Exact match"])
# Additional filters
col1, col2, col3 = st.columns(3)
with col1:
min_size = st.number_input("Min Size (MB)", min_value=0.0, value=0.0, step=0.1)
with col2:
max_size = st.number_input("Max Size (MB)", min_value=0.0, value=1000.0, step=0.1)
with col3:
date_filter = st.date_input("Modified after", value=None)
# Search results
if search_pattern:
if search_type == "Contains":
results = [b for b in blobs if search_pattern.lower() in b.name.lower()]
elif search_type == "Starts with":
results = [b for b in blobs if b.name.lower().startswith(search_pattern.lower())]
elif search_type == "Ends with":
results = [b for b in blobs if b.name.lower().endswith(search_pattern.lower())]
else: # Exact match
results = [b for b in blobs if b.name.lower() == search_pattern.lower()]
# Apply size filter
if min_size > 0 or max_size < 1000:
results = [b for b in results if b.size and min_size <= (b.size / (1024*1024)) <= max_size]
# Apply date filter
if date_filter:
results = [b for b in results if b.updated and b.updated.date() >= date_filter]
st.write(f"Found {len(results)} matching files")
if results:
# File selection with checkboxes
st.subheader("π Select Files")
selected_files = []
for i, blob in enumerate(results[:50]): # Limit to 50 for performance
col1, col2, col3 = st.columns([1, 3, 1])
with col1:
if st.checkbox("", key=f"select_{i}"):
selected_files.append(blob.name)
with col2:
st.write(f"π {blob.name}")
with col3:
if st.button("ποΈ Preview", key=f"preview_{i}"):
st.session_state.preview_file = blob.name
# Preview section
if hasattr(st.session_state, 'preview_file'):
st.subheader("πΌοΈ File Preview")
preview_blob = bucket.blob(st.session_state.preview_file)
if is_image_file(st.session_state.preview_file):
try:
# Generate signed URL for image preview
signed_url = preview_blob.generate_signed_url(expiration=timedelta(hours=1), method="GET")
st.image(signed_url, caption=st.session_state.preview_file, use_column_width=True)
except Exception as e:
st.error(f"Could not load image: {str(e)}")
elif is_video_file(st.session_state.preview_file):
try:
signed_url = preview_blob.generate_signed_url(expiration=timedelta(hours=1), method="GET")
st.video(signed_url)
except Exception as e:
st.error(f"Could not load video: {str(e)}")
else:
st.info("Preview not available for this file type")
# File details
st.write("**File Details:**")
size_mb = (preview_blob.size / (1024*1024)) if preview_blob.size else 0
st.write(f"- Size: {preview_blob.size or 'Unknown'} bytes ({size_mb:.2f} MB)")
st.write(f"- Content Type: {preview_blob.content_type or 'Unknown'}")
st.write(f"- Created: {preview_blob.time_created or 'Unknown'}")
st.write(f"- Updated: {preview_blob.updated or 'Unknown'}")
# Bulk actions for selected files
if selected_files:
st.subheader("β‘ Bulk Actions")
col1, col2, col3 = st.columns(3)
with col1:
if st.button("π₯ Download Selected"):
if len(selected_files) == 1:
# Single file download
blob = bucket.blob(selected_files[0])
signed_url = blob.generate_signed_url(expiration=timedelta(hours=1), method="GET")
st.markdown(f"[Download {selected_files[0]}]({signed_url})")
else:
# Multiple files - create zip
with st.spinner("Creating zip file..."):
zip_buffer = create_zip_file(selected_files, bucket)
st.download_button(
f"π¦ Download {len(selected_files)} files as ZIP",
zip_buffer.getvalue(),
"selected_files.zip",
"application/zip"
)
with col2:
if st.button("π Generate Signed URLs"):
selected_blobs = [bucket.blob(name) for name in selected_files]
urls = generate_signed_urls(selected_blobs)
for url_data in urls:
st.write(f"**{url_data['filename']}** β [Open]({url_data['signed_url']})")
with col3:
if st.button("π Export Metadata"):
selected_blobs = [bucket.blob(name) for name in selected_files]
metadata_df = create_file_dataframe(selected_blobs)
csv = metadata_df.to_csv(index=False)
st.download_button("Download Metadata CSV", csv, "selected_files_metadata.csv", "text/csv")
elif selected_menu == "π₯ Bulk Download":
st.header("π₯ Bulk Download")
# Download options
col1, col2 = st.columns(2)
with col1:
download_type = st.radio("Download Type", ["By Folder", "By Selection", "By Date Range", "By File Type"])
with col2:
if download_type == "By Folder":
folders = list(set(get_folder_path(blob.name) for blob in blobs if get_folder_path(blob.name)))
selected_folder = st.selectbox("Select Folder", folders)
if selected_folder:
folder_files = [blob.name for blob in blobs if get_folder_path(blob.name) == selected_folder]
st.write(f"Files in folder: {len(folder_files)}")
elif download_type == "By File Type":
file_type = st.selectbox("File Type", ["Images", "Videos", "Documents", "All"])
if file_type == "Images":
type_files = [blob.name for blob in blobs if is_image_file(blob.name)]
elif file_type == "Videos":
type_files = [blob.name for blob in blobs if is_video_file(blob.name)]
elif file_type == "Documents":
doc_extensions = {'.pdf', '.doc', '.docx', '.txt', '.rtf', '.odt'}
type_files = [blob.name for blob in blobs if get_file_extension(blob.name) in doc_extensions]
else:
type_files = [blob.name for blob in blobs]
st.write(f"Files of type {file_type}: {len(type_files)}")
elif download_type == "By Date Range":
col1, col2 = st.columns(2)
with col1:
start_date = st.date_input("Start Date")
with col2:
end_date = st.date_input("End Date")
if start_date and end_date:
date_files = [blob.name for blob in blobs if blob.updated and start_date <= blob.updated.date() <= end_date]
st.write(f"Files in date range: {len(date_files)}")
# Download button
if st.button("π¦ Create Download Package"):
if download_type == "By Folder" and selected_folder:
files_to_download = folder_files
elif download_type == "By File Type":
files_to_download = type_files
elif download_type == "By Date Range" and start_date and end_date:
files_to_download = date_files
else:
st.warning("Please select appropriate options")
files_to_download = []
if files_to_download:
with st.spinner(f"Creating zip file with {len(files_to_download)} files..."):
zip_buffer = create_zip_file(files_to_download, bucket)
st.download_button(
f"π¦ Download {len(files_to_download)} files",
zip_buffer.getvalue(),
f"bulk_download_{download_type.lower().replace(' ', '_')}.zip",
"application/zip"
)
elif selected_menu == "π Export Links & Metadata":
st.header("π Export Links & Metadata")
# Export options
col1, col2 = st.columns(2)
with col1:
export_type = st.selectbox("Export Type", [
"Private Signed URLs",
"Public URLs (if bucket is public)",
"File Names Only",
"Complete Metadata",
"All Data (CSV)",
"All Data (JSON)"
])
with col2:
expiration_hours = st.number_input("URL Expiration (hours)", min_value=1, max_value=24, value=1)
# File selection
st.subheader("π Select Files to Export")
select_all = st.checkbox("Select All Files")
if select_all:
selected_files = [blob.name for blob in blobs]
else:
# Manual selection
selected_files = []
for i, blob in enumerate(blobs[:100]): # Limit for performance
if st.checkbox(blob.name, key=f"export_{i}"):
selected_files.append(blob.name)
st.write(f"Selected {len(selected_files)} files")
if selected_files and st.button("π€ Generate Export"):
selected_blobs = [bucket.blob(name) for name in selected_files]
if export_type == "Private Signed URLs":
urls = generate_signed_urls(selected_blobs, expiration_hours)
export_data = "\n".join([f"{url['filename']},{url['signed_url']}" for url in urls])
st.download_button("Download URLs CSV", export_data, "signed_urls.csv", "text/csv")
elif export_type == "File Names Only":
names_data = "\n".join(selected_files)
st.download_button("Download Names TXT", names_data, "file_names.txt", "text/plain")
elif export_type == "Complete Metadata":
df = create_file_dataframe(selected_blobs)
csv = df.to_csv(index=False)
st.download_button("Download Metadata CSV", csv, "complete_metadata.csv", "text/csv")
elif export_type == "All Data (CSV)":
df = create_file_dataframe(selected_blobs)
# Add signed URLs
urls = generate_signed_urls(selected_blobs, expiration_hours)
url_dict = {url['filename']: url['signed_url'] for url in urls}
df['Signed URL'] = df['Name'].map(url_dict)
csv = df.to_csv(index=False)
st.download_button("Download All Data CSV", csv, "all_data.csv", "text/csv")
elif export_type == "All Data (JSON)":
df = create_file_dataframe(selected_blobs)
urls = generate_signed_urls(selected_blobs, expiration_hours)
url_dict = {url['filename']: url['signed_url'] for url in urls}
df['Signed URL'] = df['Name'].map(url_dict)
json_data = df.to_json(orient='records', indent=2)
st.download_button("Download All Data JSON", json_data, "all_data.json", "application/json")
elif selected_menu == "π€ Advanced Upload":
st.header("π€ Advanced Upload")
# Get all folders for selection
all_folders = get_all_folders(blobs)
# Upload type selection
upload_type = st.radio("Upload Type:", ["Single File", "Multiple Files", "Bulk Upload"])
if upload_type == "Single File":
st.subheader("π Single File Upload")
col1, col2 = st.columns([2, 1])
with col1:
uploaded_file = st.file_uploader("Choose a file", type=None)
with col2:
# Folder selection
st.write("**Destination Folder:**")
folder_option = st.radio("Folder:", ["Root Directory", "Select Existing Folder", "Create New Folder"])
if folder_option == "Select Existing Folder":
if all_folders:
selected_folder = st.selectbox("Choose folder:", all_folders)
folder_path = selected_folder + "/" if selected_folder else ""
else:
st.info("No folders available")
folder_path = ""
elif folder_option == "Create New Folder":
new_folder = st.text_input("New folder name:", placeholder="folder/subfolder")
folder_path = new_folder + "/" if new_folder else ""
else:
folder_path = ""
if uploaded_file:
# File name options
col1, col2 = st.columns(2)
with col1:
use_original_name = st.checkbox("Use original filename", value=True)
with col2:
if not use_original_name:
custom_name = st.text_input("Custom filename:", value=uploaded_file.name)
else:
custom_name = uploaded_file.name
# Final path
final_path = folder_path + custom_name
st.write(f"**Upload Path:** `{final_path}`")
if st.button("π€ Upload File", type="primary"):
try:
blob = bucket.blob(final_path)
blob.upload_from_file(uploaded_file, rewind=True)
st.success(f"β
Successfully uploaded: {final_path}")
st.rerun()
except Exception as e:
st.error(f"β Upload failed: {str(e)}")
elif upload_type == "Multiple Files":
st.subheader("π Multiple Files Upload")
col1, col2 = st.columns([2, 1])
with col1:
uploaded_files = st.file_uploader("Choose multiple files", accept_multiple_files=True, type=None)
with col2:
# Folder selection
st.write("**Destination Folder:**")
folder_option = st.radio("Folder:", ["Root Directory", "Select Existing Folder", "Create New Folder"], key="multi_folder")
if folder_option == "Select Existing Folder":
if all_folders:
selected_folder = st.selectbox("Choose folder:", all_folders, key="multi_select")
folder_path = selected_folder + "/" if selected_folder else ""
else:
st.info("No folders available")
folder_path = ""
elif folder_option == "Create New Folder":
new_folder = st.text_input("New folder name:", placeholder="folder/subfolder", key="multi_new")
folder_path = new_folder + "/" if new_folder else ""
else:
folder_path = ""
if uploaded_files:
st.write(f"**Files to upload:** {len(uploaded_files)}")
for file in uploaded_files:
st.write(f"β’ {file.name}")
st.write(f"**Upload to:** `{folder_path}`")
if st.button("π€ Upload All Files", type="primary"):
success_count = 0
error_count = 0
progress_bar = st.progress(0)
status_text = st.empty()
for i, uploaded_file in enumerate(uploaded_files):
try:
final_path = folder_path + uploaded_file.name