tuhbooh commited on
Commit
5dc13d9
·
verified ·
1 Parent(s): 835997f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +133 -0
app.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import shutil
4
+ import zipfile
5
+ import gradio as gr
6
+ from fastapi import FastAPI
7
+ import uvicorn
8
+
9
+ # --- CẤU HÌNH HỆ THỐNG ---
10
+ BASE_UPLOAD_DIR = "bins"
11
+ EXPIRATION_HOURS = 24
12
+
13
+ if not os.path.exists(BASE_UPLOAD_DIR):
14
+ os.makedirs(BASE_UPLOAD_DIR)
15
+
16
+ # --- CÁC HÀM XỬ LÝ (BACKEND) ---
17
+
18
+ def clean_old_bins():
19
+ """Tự động xóa các Bin cũ hơn 24h"""
20
+ now = time.time()
21
+ cutoff = now - (EXPIRATION_HOURS * 3600)
22
+ if os.path.exists(BASE_UPLOAD_DIR):
23
+ for bin_id in os.listdir(BASE_UPLOAD_DIR):
24
+ bin_path = os.path.join(BASE_UPLOAD_DIR, bin_id)
25
+ if os.path.getmtime(bin_path) < cutoff:
26
+ shutil.rmtree(bin_path)
27
+
28
+ def upload_to_bin(bin_id, files, progress=gr.Progress()):
29
+ clean_old_bins()
30
+ if not bin_id or not files:
31
+ return "⚠️ Thiếu mã Bin hoặc File!", None
32
+
33
+ bin_id = bin_id.strip()
34
+ bin_path = os.path.join(BASE_UPLOAD_DIR, bin_id)
35
+ if not os.path.exists(bin_path):
36
+ os.makedirs(bin_path)
37
+
38
+ total_files = len(files)
39
+ uploaded_list = []
40
+
41
+ for i, file in enumerate(files):
42
+ # Hiển thị % xử lý trên Server
43
+ progress((i + 1) / total_files, desc=f"Đang lưu file {i+1}/{total_files}...")
44
+ dest_path = os.path.join(bin_path, os.path.basename(file.name))
45
+ shutil.copy(file.name, dest_path)
46
+ uploaded_list.append(dest_path)
47
+
48
+ os.utime(bin_path, None) # Reset thời gian tồn tại (gia hạn 24h)
49
+ return f"✅ Đã tải lên thành công {total_files} file vào Bin: {bin_id}", uploaded_list
50
+
51
+ def get_bin_files(bin_id):
52
+ clean_old_bins()
53
+ if not bin_id: return "⚠️ Vui lòng nhập mã Bin!", None
54
+
55
+ bin_path = os.path.join(BASE_UPLOAD_DIR, bin_id.strip())
56
+ if not os.path.exists(bin_path):
57
+ return f"❌ Bin '{bin_id}' không tồn tại hoặc đã hết hạn.", None
58
+
59
+ files = [os.path.join(bin_path, f) for f in os.listdir(bin_path) if f != "all_files.zip"]
60
+ return f"📂 Tìm thấy {len(files)} file trong Bin: {bin_id}", files
61
+
62
+ def download_all_zip(bin_id, progress=gr.Progress()):
63
+ if not bin_id: return None
64
+ bin_path = os.path.join(BASE_UPLOAD_DIR, bin_id.strip())
65
+ if not os.path.exists(bin_path): return None
66
+
67
+ files = [f for f in os.listdir(bin_path) if f != "all_files.zip"]
68
+ if not files: return None
69
+
70
+ zip_path = os.path.join(bin_path, "all_files.zip")
71
+ with zipfile.ZipFile(zip_path, 'w') as zipf:
72
+ for i, f in enumerate(files):
73
+ progress((i + 1) / len(files), desc="Đang nén file...")
74
+ zipf.write(os.path.join(bin_path, f), f)
75
+
76
+ return zip_path
77
+
78
+ def delete_bin(bin_id):
79
+ if not bin_id: return "⚠️ Nhập mã Bin cần xóa!", None
80
+ bin_path = os.path.join(BASE_UPLOAD_DIR, bin_id.strip())
81
+ if os.path.exists(bin_path):
82
+ shutil.rmtree(bin_path)
83
+ return f"🗑️ Đã xóa vĩnh viễn Bin: {bin_id}", None
84
+ return "❌ Bin không tồn tại.", None
85
+
86
+ # --- GIAO DIỆN GRADIO ---
87
+
88
+ with gr.Blocks(theme=gr.themes.Soft(), title="HF FileBin Pro") as demo:
89
+ gr.Markdown("# 🚀 HF FileBin Pro (Bản Full)")
90
+ gr.Markdown(f"Dịch vụ lưu trữ file tạm thời (Tự xóa sau {EXPIRATION_HOURS}h không hoạt động)")
91
+
92
+ with gr.Row():
93
+ bin_id_input = gr.Textbox(
94
+ label="Mã Bin (Private ID)",
95
+ placeholder="Nhập mã bí mật để tạo hoặc truy cập...",
96
+ info="Ai có mã này mới có thể xem/tải file."
97
+ )
98
+
99
+ with gr.Row():
100
+ with gr.Column(scale=1):
101
+ file_input = gr.File(label="Chọn Files (Hỗ trợ kéo thả)", file_count="multiple")
102
+ btn_upload = gr.Button("📤 Tải lên & Xử lý", variant="primary")
103
+
104
+ with gr.Column(scale=1):
105
+ status_msg = gr.Textbox(label="Thông báo hệ thống", interactive=False)
106
+ file_output = gr.File(label="Danh sách file khả dụng", file_count="multiple")
107
+
108
+ with gr.Row():
109
+ btn_access = gr.Button("🔍 Kiểm tra Bin")
110
+ btn_zip = gr.Button("📦 Tải ZIP (Tất cả)")
111
+ btn_delete = gr.Button("🗑️ Xóa Bin", variant="stop")
112
+
113
+ # Gán sự kiện
114
+ btn_upload.click(fn=upload_to_bin, inputs=[bin_id_input, file_input], outputs=[status_msg, file_output])
115
+ btn_access.click(fn=get_bin_files, inputs=[bin_id_input], outputs=[status_msg, file_output])
116
+ btn_zip.click(fn=download_all_zip, inputs=[bin_id_input], outputs=[file_output])
117
+ btn_delete.click(fn=delete_bin, inputs=[bin_id_input], outputs=[status_msg, file_output])
118
+
119
+ # --- TÍCH HỢP FASTAPI CHO UPTIME ROBOT ---
120
+
121
+ fastapi_app = FastAPI()
122
+
123
+ @fastapi_app.get("/health")
124
+ def health_check():
125
+ """Endpoint dành riêng cho Uptime Robot ping"""
126
+ return {"status": "online", "active_bins": len(os.listdir(BASE_UPLOAD_DIR)) if os.path.exists(BASE_UPLOAD_DIR) else 0}
127
+
128
+ # Mount Gradio vào FastAPI
129
+ app = gr.mount_gradio_app(fastapi_app, demo, path="/")
130
+
131
+ if __name__ == "__main__":
132
+ # Chạy trên port 7860 (Port mặc định của Hugging Face)
133
+ uvicorn.run(app, host="0.0.0.0", port=7860)