Upload db.py with huggingface_hub
Browse files
db.py
CHANGED
|
@@ -525,6 +525,54 @@ def get_storage_stats():
|
|
| 525 |
return {'count': len(files), 'size_mb': round(total_size / 1024 / 1024, 2)}
|
| 526 |
|
| 527 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 528 |
def register_user(username, password, display_name=''):
|
| 529 |
"""註冊新使用者"""
|
| 530 |
backup_db()
|
|
|
|
| 525 |
return {'count': len(files), 'size_mb': round(total_size / 1024 / 1024, 2)}
|
| 526 |
|
| 527 |
|
| 528 |
+
def list_uploads():
|
| 529 |
+
"""列出 uploads/ 所有檔案(name, size_kb, mtime ISO 字串),按 mtime 新→舊"""
|
| 530 |
+
d = get_upload_dir()
|
| 531 |
+
files = list(d.glob('*.xls')) + list(d.glob('*.xlsx')) + list(d.glob('*.csv'))
|
| 532 |
+
files.sort(key=lambda p: p.stat().st_mtime, reverse=True)
|
| 533 |
+
out = []
|
| 534 |
+
for f in files:
|
| 535 |
+
st = f.stat()
|
| 536 |
+
out.append({
|
| 537 |
+
'name': f.name,
|
| 538 |
+
'size_kb': round(st.st_size / 1024, 1),
|
| 539 |
+
'mtime': datetime.fromtimestamp(st.st_mtime).strftime('%Y-%m-%d %H:%M'),
|
| 540 |
+
})
|
| 541 |
+
return out
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
def delete_upload(filename):
|
| 545 |
+
"""刪除 uploads/<filename>(本地 + 同步刪除 repo 對應檔案)。"""
|
| 546 |
+
d = get_upload_dir()
|
| 547 |
+
# 防目錄穿越
|
| 548 |
+
safe_name = os.path.basename(filename)
|
| 549 |
+
p = d / safe_name
|
| 550 |
+
if not p.exists():
|
| 551 |
+
return False
|
| 552 |
+
try:
|
| 553 |
+
p.unlink()
|
| 554 |
+
except Exception as e:
|
| 555 |
+
logger.warning(f'local delete failed: {e}')
|
| 556 |
+
return False
|
| 557 |
+
token = os.environ.get('HF_TOKEN', '')
|
| 558 |
+
username = os.environ.get('HF_USERNAME', '')
|
| 559 |
+
if token and username:
|
| 560 |
+
def _go():
|
| 561 |
+
try:
|
| 562 |
+
from huggingface_hub import HfApi
|
| 563 |
+
api = HfApi(token=token)
|
| 564 |
+
api.delete_file(
|
| 565 |
+
path_in_repo=f'uploads/{safe_name}',
|
| 566 |
+
repo_id=f'{username}/pradsa',
|
| 567 |
+
repo_type='space',
|
| 568 |
+
)
|
| 569 |
+
logger.info(f'Deleted uploads/{safe_name} from repo')
|
| 570 |
+
except Exception as e:
|
| 571 |
+
logger.warning(f'repo delete failed: {e}')
|
| 572 |
+
threading.Thread(target=_go, daemon=True).start()
|
| 573 |
+
return True
|
| 574 |
+
|
| 575 |
+
|
| 576 |
def register_user(username, password, display_name=''):
|
| 577 |
"""註冊新使用者"""
|
| 578 |
backup_db()
|