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etime
|
| 6 |
+
|
| 7 |
+
# --- Configuration ---
|
| 8 |
+
UPLOAD_DIR = "shared_files"
|
| 9 |
+
# MAX_STORAGE_GB = 1
|
| 10 |
+
# MAX_STORAGE_BYTES = MAX_STORAGE_GB * 1024 * 1024 * 1024
|
| 11 |
+
# OWNER_PASSWORD = os.environ.get("OWNER_PASSWORD")
|
| 12 |
+
|
| 13 |
+
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
| 14 |
+
|
| 15 |
+
# def get_dir_size(path):
|
| 16 |
+
# total_size = 0
|
| 17 |
+
# for dirpath, _, filenames in os.walk(path):
|
| 18 |
+
# for f in filenames:
|
| 19 |
+
# total_size += os.path.getsize(os.path.join(dirpath, f))
|
| 20 |
+
# return total_size
|
| 21 |
+
|
| 22 |
+
def get_file_info():
|
| 23 |
+
file_data = []
|
| 24 |
+
file_list_for_dropdown = []
|
| 25 |
+
for f in os.listdir(UPLOAD_DIR):
|
| 26 |
+
path = os.path.join(UPLOAD_DIR, f)
|
| 27 |
+
if os.path.isfile(path):
|
| 28 |
+
stats = os.stat(path)
|
| 29 |
+
dt_object = datetime.fromtimestamp(stats.st_mtime)
|
| 30 |
+
|
| 31 |
+
# --- PARSING LOGIC ---
|
| 32 |
+
# Format: Timestamp_UserName_OriginalName.ext
|
| 33 |
+
parts = f.split("_", 2)
|
| 34 |
+
if len(parts) == 3:
|
| 35 |
+
user_name = parts[1]
|
| 36 |
+
display_name = parts[2]
|
| 37 |
+
else:
|
| 38 |
+
user_name = "Anonymous"
|
| 39 |
+
display_name = parts[1] if len(parts) > 1 else f
|
| 40 |
+
|
| 41 |
+
file_data.append({
|
| 42 |
+
"Filename": display_name,
|
| 43 |
+
"Uploaded By": user_name,
|
| 44 |
+
"Date": dt_object.strftime("%Y-%m-%d"),
|
| 45 |
+
"Time": dt_object.strftime("%H:%M:%S"),
|
| 46 |
+
"Size (MB)": round(stats.st_size / (1024 * 1024), 2),
|
| 47 |
+
"mtime": stats.st_mtime
|
| 48 |
+
})
|
| 49 |
+
file_list_for_dropdown.append(f)
|
| 50 |
+
|
| 51 |
+
df = pd.DataFrame(file_data)
|
| 52 |
+
# current_bytes = get_dir_size(UPLOAD_DIR)
|
| 53 |
+
# usage_pct = (current_bytes / MAX_STORAGE_BYTES) * 100
|
| 54 |
+
# status_msg = f"π Storage Usage: {round(current_bytes/(1024**3), 3)}GB / {MAX_STORAGE_GB}GB ({round(usage_pct, 1)}%)"
|
| 55 |
+
|
| 56 |
+
# if df.empty:
|
| 57 |
+
# return pd.DataFrame(columns=["Filename", "Uploaded By", "Date", "Time", "Size (MB)"]), status_msg, []
|
| 58 |
+
|
| 59 |
+
sorted_df = df.sort_values(by="mtime", ascending=False).drop(columns=['mtime'])
|
| 60 |
+
return sorted_df, status_msg, file_list_for_dropdown
|
| 61 |
+
|
| 62 |
+
def upload_and_refresh(uploaded_files, user_name):
|
| 63 |
+
if not user_name or user_name.strip() == "":
|
| 64 |
+
user_name = "Anonymous"
|
| 65 |
+
|
| 66 |
+
# Clean user name to prevent filename errors
|
| 67 |
+
user_name = "".join(x for x in user_name if x.isalnum())
|
| 68 |
+
|
| 69 |
+
if uploaded_files:
|
| 70 |
+
if not isinstance(uploaded_files, list):
|
| 71 |
+
uploaded_files = [uploaded_files]
|
| 72 |
+
for file in uploaded_files:
|
| 73 |
+
file_size = os.stat(file.name).st_size
|
| 74 |
+
|
| 75 |
+
# Janitor to maintain 1GB limit
|
| 76 |
+
while get_dir_size(UPLOAD_DIR) + file_size > MAX_STORAGE_BYTES:
|
| 77 |
+
oldest_files = sorted([os.path.join(UPLOAD_DIR, f) for f in os.listdir(UPLOAD_DIR)], key=os.path.getmtime)
|
| 78 |
+
if not oldest_files: break
|
| 79 |
+
os.remove(oldest_files[0])
|
| 80 |
+
|
| 81 |
+
timestamp = datetime.now().strftime("%H%M%S")
|
| 82 |
+
# New format: Time_User_Filename
|
| 83 |
+
safe_filename = f"{timestamp}_{user_name}_{os.path.basename(file.name)}"
|
| 84 |
+
shutil.copy(file.name, os.path.join(UPLOAD_DIR, safe_filename))
|
| 85 |
+
|
| 86 |
+
df, status, files = get_file_info()
|
| 87 |
+
# Returns None for file_input and empty string for name_input to clear them
|
| 88 |
+
## return None, "", df, status, gr.update(choices=files)
|
| 89 |
+
return None, "", df, gr.update(choices=files)
|
| 90 |
+
|
| 91 |
+
# def delete_selected_files(password, files_to_delete):
|
| 92 |
+
# if password != OWNER_PASSWORD:
|
| 93 |
+
# return "β Incorrect Password."
|
| 94 |
+
# if not files_to_delete:
|
| 95 |
+
# return "β οΈ No files selected."
|
| 96 |
+
# for f in files_to_delete:
|
| 97 |
+
# path = os.path.join(UPLOAD_DIR, f)
|
| 98 |
+
# if os.path.exists(path):
|
| 99 |
+
# os.remove(path)
|
| 100 |
+
# return f"β
Deleted {len(files_to_delete)} file(s)."
|
| 101 |
+
|
| 102 |
+
with gr.Blocks(title="File Exchange") as demo:
|
| 103 |
+
gr.Markdown("# π File Exchange")
|
| 104 |
+
storage_label = gr.Markdown("π Storage Usage: Calculating...")
|
| 105 |
+
|
| 106 |
+
with gr.Row():
|
| 107 |
+
with gr.Column(scale=1):
|
| 108 |
+
name_input = gr.Textbox(label="Your Name (Optional)")
|
| 109 |
+
file_input = gr.File(label="Select Files", file_count="multiple", type="filepath")
|
| 110 |
+
upload_btn = gr.Button("Upload & Share", variant="primary")
|
| 111 |
+
|
| 112 |
+
with gr.Accordion("Owner Controls", open=False):
|
| 113 |
+
pass_input = gr.Textbox(label="Owner Password", type="password")
|
| 114 |
+
delete_dropdown = gr.Dropdown(label="Select Files to Delete", choices=[], multiselect=True)
|
| 115 |
+
delete_btn = gr.Button("π Delete Selected", variant="stop")
|
| 116 |
+
admin_status = gr.Markdown("")
|
| 117 |
+
|
| 118 |
+
with gr.Column(scale=2):
|
| 119 |
+
file_table = gr.Dataframe(label="Current Files", interactive=False)
|
| 120 |
+
download_manager = gr.File(label="Download List", file_count="multiple", interactive=False)
|
| 121 |
+
refresh_btn = gr.Button("π Refresh List")
|
| 122 |
+
|
| 123 |
+
def full_refresh():
|
| 124 |
+
df, status, files = get_file_info()
|
| 125 |
+
paths = [os.path.join(UPLOAD_DIR, f) for f in files]
|
| 126 |
+
return df, status, gr.update(choices=files), paths
|
| 127 |
+
|
| 128 |
+
demo.load(fn=full_refresh, outputs=[file_table, storage_label, delete_dropdown, download_manager])
|
| 129 |
+
|
| 130 |
+
upload_btn.click(
|
| 131 |
+
fn=upload_and_refresh,
|
| 132 |
+
inputs=[file_input, name_input],
|
| 133 |
+
outputs=[file_input, name_input, file_table, delete_dropdown]
|
| 134 |
+
).then(fn=lambda: [os.path.join(UPLOAD_DIR, f) for f in os.listdir(UPLOAD_DIR)], outputs=download_manager)
|
| 135 |
+
|
| 136 |
+
# upload_btn.click(
|
| 137 |
+
# fn=upload_and_refresh,
|
| 138 |
+
# inputs=[file_input, name_input],
|
| 139 |
+
# outputs=[file_input, name_input, file_table, storage_label, delete_dropdown]
|
| 140 |
+
# ).then(fn=lambda: [os.path.join(UPLOAD_DIR, f) for f in os.listdir(UPLOAD_DIR)], outputs=download_manager)
|
| 141 |
+
|
| 142 |
+
# delete_btn.click(
|
| 143 |
+
# fn=delete_selected_files,
|
| 144 |
+
# inputs=[pass_input, delete_dropdown],
|
| 145 |
+
# outputs=admin_status
|
| 146 |
+
# ).then(fn=full_refresh, outputs=[file_table, storage_label, delete_dropdown, download_manager])
|
| 147 |
+
|
| 148 |
+
refresh_btn.click(fn=full_refresh, outputs=[file_table, storage_label, delete_dropdown, download_manager])
|
| 149 |
+
|
| 150 |
+
demo.launch()
|