cronjob / app.py
testdeep123's picture
Update app.py
524f481 verified
raw
history blame
20.5 kB
import os
import tempfile
from flask import Flask, render_template_string, request, redirect, send_file, jsonify
from huggingface_hub import HfApi, hf_hub_download, upload_file, delete_file
# Environment
REPO_ID = os.getenv("REPO_ID")
HF_TOKEN = os.getenv("HF_TOKEN")
app = Flask(__name__)
api = HfApi()
TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>HuggingFace Drive - {{ path or 'Root' }}</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background: linear-gradient(135deg, #0f0f23 0%, #1a1a2e 100%);
color: #e2e8f0;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
min-height: 100vh;
overflow-x: hidden;
}
.container {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
.header {
background: rgba(255, 255, 255, 0.05);
backdrop-filter: blur(10px);
border-radius: 16px;
padding: 24px;
margin-bottom: 24px;
border: 1px solid rgba(255, 255, 255, 0.1);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}
.title {
font-size: 2rem;
font-weight: 700;
margin-bottom: 16px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.breadcrumb {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 20px;
flex-wrap: wrap;
}
.breadcrumb-item {
background: rgba(255, 255, 255, 0.1);
color: #94a3b8;
padding: 6px 12px;
border-radius: 20px;
font-size: 0.875rem;
cursor: pointer;
transition: all 0.3s ease;
border: 1px solid rgba(255, 255, 255, 0.1);
}
.breadcrumb-item:hover {
background: rgba(102, 126, 234, 0.2);
color: #e2e8f0;
transform: translateY(-1px);
}
.breadcrumb-item.active {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.breadcrumb-separator {
color: #64748b;
font-size: 0.875rem;
}
.actions {
display: flex;
gap: 12px;
margin-bottom: 24px;
flex-wrap: wrap;
}
.upload-container {
position: relative;
overflow: hidden;
display: inline-block;
}
.file-input {
position: absolute;
left: -9999px;
opacity: 0;
}
.btn {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
padding: 12px 24px;
border-radius: 12px;
cursor: pointer;
font-weight: 600;
font-size: 0.875rem;
transition: all 0.3s ease;
box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
border: 1px solid rgba(255, 255, 255, 0.1);
}
.btn:hover {
transform: translateY(-2px);
box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
}
.btn-secondary {
background: rgba(255, 255, 255, 0.1);
color: #e2e8f0;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}
.btn-secondary:hover {
background: rgba(255, 255, 255, 0.15);
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3);
}
.file-grid {
display: grid;
gap: 16px;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
}
.file-item {
background: rgba(255, 255, 255, 0.05);
backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 16px;
padding: 20px;
transition: all 0.3s ease;
cursor: pointer;
position: relative;
overflow: hidden;
}
.file-item::before {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
transition: left 0.5s ease;
}
.file-item:hover::before {
left: 100%;
}
.file-item:hover {
transform: translateY(-4px);
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.3);
border-color: rgba(102, 126, 234, 0.3);
}
.file-content {
display: flex;
align-items: center;
justify-content: space-between;
position: relative;
z-index: 2;
}
.file-info {
display: flex;
align-items: center;
gap: 12px;
flex: 1;
}
.file-icon {
font-size: 1.5rem;
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 10px;
background: rgba(255, 255, 255, 0.1);
}
.folder-icon {
background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
}
.file-name {
font-weight: 500;
font-size: 1rem;
color: #f1f5f9;
}
.dropdown {
position: relative;
}
.dropdown-toggle {
background: rgba(255, 255, 255, 0.1);
border: none;
color: #94a3b8;
padding: 8px;
border-radius: 8px;
cursor: pointer;
transition: all 0.3s ease;
font-size: 1.25rem;
width: 36px;
height: 36px;
display: flex;
align-items: center;
justify-content: center;
}
.dropdown-toggle:hover {
background: rgba(255, 255, 255, 0.2);
color: #e2e8f0;
}
.dropdown-menu {
position: absolute;
top: 100%;
right: 0;
background: rgba(15, 15, 35, 0.95);
backdrop-filter: blur(20px);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 12px;
padding: 8px;
min-width: 150px;
opacity: 0;
visibility: hidden;
transform: translateY(-10px);
transition: all 0.3s ease;
z-index: 1000;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
}
.dropdown.active .dropdown-menu {
opacity: 1;
visibility: visible;
transform: translateY(0);
}
.dropdown-item {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 12px;
border-radius: 8px;
cursor: pointer;
transition: all 0.2s ease;
font-size: 0.875rem;
color: #cbd5e1;
}
.dropdown-item:hover {
background: rgba(255, 255, 255, 0.1);
color: #f1f5f9;
}
.dropdown-item.danger:hover {
background: rgba(239, 68, 68, 0.2);
color: #fca5a5;
}
/* Modal Styles */
.modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.7);
backdrop-filter: blur(5px);
display: flex;
align-items: center;
justify-content: center;
z-index: 2000;
opacity: 0;
visibility: hidden;
transition: all 0.3s ease;
}
.modal-overlay.active {
opacity: 1;
visibility: visible;
}
.modal {
background: rgba(15, 15, 35, 0.95);
backdrop-filter: blur(20px);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 20px;
padding: 32px;
max-width: 400px;
width: 90%;
transform: scale(0.8);
transition: all 0.3s ease;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.6);
}
.modal-overlay.active .modal {
transform: scale(1);
}
.modal-title {
font-size: 1.25rem;
font-weight: 600;
margin-bottom: 16px;
color: #f1f5f9;
}
.modal-input {
width: 100%;
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 12px;
padding: 12px 16px;
color: #f1f5f9;
font-size: 1rem;
margin-bottom: 20px;
}
.modal-input:focus {
outline: none;
border-color: #667eea;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.modal-actions {
display: flex;
gap: 12px;
justify-content: flex-end;
}
.btn-danger {
background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
box-shadow: 0 4px 15px rgba(239, 68, 68, 0.3);
}
.btn-danger:hover {
box-shadow: 0 8px 25px rgba(239, 68, 68, 0.4);
}
/* Loading Animation */
.loading {
display: inline-block;
width: 20px;
height: 20px;
border: 2px solid rgba(255, 255, 255, 0.3);
border-radius: 50%;
border-top-color: #667eea;
animation: spin 1s ease-in-out infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
/* Responsive Design */
@media (max-width: 768px) {
.container {
padding: 16px;
}
.file-grid {
grid-template-columns: 1fr;
}
.actions {
flex-direction: column;
}
.breadcrumb {
flex-direction: column;
align-items: flex-start;
}
}
/* Custom Scrollbar */
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track {
background: rgba(255, 255, 255, 0.1);
}
::-webkit-scrollbar-thumb {
background: rgba(102, 126, 234, 0.5);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: rgba(102, 126, 234, 0.7);
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1 class="title">🚀 HuggingFace Drive</h1>
<!-- Breadcrumb Navigation -->
<div class="breadcrumb">
<span class="breadcrumb-item {{ 'active' if not path else '' }}" onclick="nav('')">
🏠 Home
</span>
{% if path %}
{% set parts = path.split('/') %}
{% for i in range(parts|length) %}
<span class="breadcrumb-separator">›</span>
{% set current_path = parts[:i+1]|join('/') %}
<span class="breadcrumb-item {{ 'active' if current_path == path else '' }}"
onclick="nav('{{ current_path }}')">
📁 {{ parts[i] }}
</span>
{% endfor %}
{% endif %}
</div>
<!-- Actions -->
<div class="actions">
<form action="/upload" method="post" enctype="multipart/form-data" class="upload-container">
<input type="file" name="file" required class="file-input" id="fileInput">
<input type="hidden" name="path" value="{{ path }}">
<label for="fileInput" class="btn">
📤 Upload File
</label>
</form>
<button class="btn btn-secondary" onclick="createFolder('{{ path }}')">
📁 New Folder
</button>
</div>
</div>
<!-- File Grid -->
<div class="file-grid">
{% for item in items %}
<div class="file-item">
<div class="file-content">
<div class="file-info" onclick="{% if item.type=='dir' %}nav('{{ item.path }}'){% endif %}">
<div class="file-icon {{ 'folder-icon' if item.type=='dir' else '' }}">
{{ '📁' if item.type=='dir' else '📄' }}
</div>
<div class="file-name">{{ item.name }}</div>
</div>
<div class="dropdown">
<button class="dropdown-toggle" onclick="toggleDropdown(this)">⋮</button>
<div class="dropdown-menu">
{% if item.type == 'file' %}
<div class="dropdown-item" onclick="download('{{ item.path }}')">
📥 Download
</div>
{% endif %}
<div class="dropdown-item" onclick="showRenameModal('{{ item.path }}', '{{ item.name }}')">
✏️ Rename
</div>
<div class="dropdown-item danger" onclick="showDeleteModal('{{ item.path }}')">
🗑️ Delete
</div>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
<!-- Rename Modal -->
<div class="modal-overlay" id="renameModal">
<div class="modal">
<h3 class="modal-title">Rename Item</h3>
<input type="text" class="modal-input" id="renameInput" placeholder="Enter new name">
<div class="modal-actions">
<button class="btn btn-secondary" onclick="closeModal('renameModal')">Cancel</button>
<button class="btn" onclick="confirmRename()">Rename</button>
</div>
</div>
</div>
<!-- Delete Confirmation Modal -->
<div class="modal-overlay" id="deleteModal">
<div class="modal">
<h3 class="modal-title">Confirm Deletion</h3>
<p style="margin-bottom: 20px; color: #cbd5e1;">Are you sure you want to delete this item? This action cannot be undone.</p>
<div class="modal-actions">
<button class="btn btn-secondary" onclick="closeModal('deleteModal')">Cancel</button>
<button class="btn btn-danger" onclick="confirmDelete()">Delete</button>
</div>
</div>
</div>
<script>
let currentRenamePath = '';
let currentDeletePath = '';
let activeDropdown = null;
function nav(p) {
location.href = '/?path=' + encodeURIComponent(p);
}
function download(path) {
window.open('/download?path=' + encodeURIComponent(path), '_blank');
}
function toggleDropdown(button) {
const dropdown = button.closest('.dropdown');
// Close other dropdowns
if (activeDropdown && activeDropdown !== dropdown) {
activeDropdown.classList.remove('active');
}
dropdown.classList.toggle('active');
activeDropdown = dropdown.classList.contains('active') ? dropdown : null;
}
function showRenameModal(path, currentName) {
currentRenamePath = path;
document.getElementById('renameInput').value = currentName;
showModal('renameModal');
setTimeout(() => document.getElementById('renameInput').focus(), 100);
closeAllDropdowns();
}
function showDeleteModal(path) {
currentDeletePath = path;
showModal('deleteModal');
closeAllDropdowns();
}
function showModal(modalId) {
document.getElementById(modalId).classList.add('active');
}
function closeModal(modalId) {
document.getElementById(modalId).classList.remove('active');
}
function closeAllDropdowns() {
document.querySelectorAll('.dropdown.active').forEach(dropdown => {
dropdown.classList.remove('active');
});
activeDropdown = null;
}
async function confirmRename() {
const newName = document.getElementById('renameInput').value.trim();
if (!newName) return;
try {
const response = await fetch('/rename', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
old_path: currentRenamePath,
new_path: newName
})
});
if (response.ok) {
closeModal('renameModal');
location.reload();
}
} catch (error) {
console.error('Rename failed:', error);
}
}
async function confirmDelete() {
try {
const response = await fetch('/delete', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: currentDeletePath })
});
if (response.ok) {
closeModal('deleteModal');
location.reload();
}
} catch (error) {
console.error('Delete failed:', error);
}
}
async function createFolder(currentPath) {
const name = prompt('Enter folder name:');
if (!name) return;
try {
const folderPath = currentPath ? `${currentPath}/${name}` : name;
const response = await fetch('/create_folder', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: folderPath })
});
if (response.ok) {
location.reload();
}
} catch (error) {
console.error('Create folder failed:', error);
}
}
// Close dropdowns when clicking outside
document.addEventListener('click', function(e) {
if (!e.target.closest('.dropdown')) {
closeAllDropdowns();
}
});
// Handle file input change for better UX
document.getElementById('fileInput').addEventListener('change', function(e) {
if (e.target.files.length > 0) {
e.target.closest('form').submit();
}
});
// Handle modal close on overlay click
document.querySelectorAll('.modal-overlay').forEach(overlay => {
overlay.addEventListener('click', function(e) {
if (e.target === overlay) {
overlay.classList.remove('active');
}
});
});
// Handle Enter key in rename modal
document.getElementById('renameInput').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
confirmRename();
}
});
</script>
</body>
</html>
"""
def list_folder(path=""):
prefix = path.strip("/") + ("/" if path else "")
all_files = api.list_repo_files(repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN)
seen = set()
items = []
for f in all_files:
if not f.startswith(prefix): continue
rest = f[len(prefix):]
if "/" in rest:
dir_name = rest.split("/")[0]
dir_path = (prefix + dir_name).strip("/")
if dir_path not in seen:
seen.add(dir_path)
items.append({"type":"dir","name":dir_name,"path":dir_path})
else:
items.append({"type":"file","name":rest,"path":(prefix + rest).strip("/")})
# sort dirs then files
items.sort(key=lambda x: (x["type"]!="dir", x["name"].lower()))
return items
@app.route("/", methods=["GET"])
def index():
path = request.args.get("path","").strip("/")
return render_template_string(TEMPLATE, items=list_folder(path), path=path)
@app.route("/download", methods=["GET"])
def download():
p = request.args.get("path","")
# download via hf_hub_download into /tmp
local = hf_hub_download(repo_id=REPO_ID, filename=p, repo_type="dataset", token=HF_TOKEN, cache_dir=tempfile.gettempdir())
return send_file(local, as_attachment=True, download_name=os.path.basename(p))
@app.route("/upload", methods=["POST"])
def upload():
file = request.files["file"]
path = request.form.get("path","").strip("/")
dest = f"{path}/{file.filename}".strip("/")
tmp = tempfile.NamedTemporaryFile(delete=False)
file.save(tmp.name)
upload_file(path_or_fileobj=tmp.name, path_in_repo=dest, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN)
return redirect(f"/?path={path}")
@app.route("/delete", methods=["POST"])
def delete():
d = request.get_json()["path"]
all_files = api.list_repo_files(repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN)
for f in all_files:
if f == d or f.startswith(d.rstrip("/")+"/"):
delete_file(repo_id=REPO_ID, path_in_repo=f, repo_type="dataset", token=HF_TOKEN)
return jsonify(status="ok")
@app.route("/create_folder", methods=["POST"])
def create_folder():
folder = request.get_json()["path"].strip("/")
keep = f"{folder}/.keep"
tmp = tempfile.NamedTemporaryFile(delete=False)
tmp.write(b"")
tmp.flush()
upload_file(path_or_fileobj=tmp.name, path_in_repo=keep, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN)
return jsonify(status="ok")
@app.route("/rename", methods=["POST"])
def rename():
data = request.get_json()
old, new = data["old_path"].strip("/"), data["new_path"].strip("/")
all_files = api.list_repo_files(repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN)
for f in all_files:
if f == old or f.startswith(old+"/"):
rel = f[len(old):].lstrip("/")
newp = (new + "/" + rel).strip("/")
local = hf_hub_download(repo_id=REPO_ID, filename=f, repo_type="dataset",
token=HF_TOKEN, cache_dir=tempfile.gettempdir())
upload_file(path_or_fileobj=local, path_in_repo=newp, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN)
delete_file(repo_id=REPO_ID, path_in_repo=f, repo_type="dataset", token=HF_TOKEN)
return jsonify(status="ok")
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=7860)