Update app.py
Browse files
app.py
CHANGED
|
@@ -343,7 +343,7 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
|
|
| 343 |
<div id="progress-container"><div id="progress-bar"></div></div>
|
| 344 |
<div class="file-grid" id="file-container">
|
| 345 |
{% for item in items %}
|
| 346 |
-
<div class="item {{ item.type }}" data-id="{{ item.id }}" data-type="{{ item.type }}" {% if item.type != 'folder' %}onclick="openModal('{{ hf_file_url_jinja(item.path) if item.file_type not in ['text', 'pdf'] else (url_for('get_text_content_tma', file_id=item.id) if item.file_type == 'text' else hf_file_url_jinja(item.path, True)) }}', '{{ item.file_type }}', '{{ item.id }}')"{% else %}onclick="window.Telegram.WebApp.HapticFeedback.impactOccurred('light'); window.location.href='{{ url_for('tma_dashboard', folder_id=item.id) }}'"{% endif %}>
|
| 347 |
<div class="item-preview-wrapper">
|
| 348 |
{% if item.type == 'folder' %}
|
| 349 |
<div class="item-preview"><i class="fa-solid fa-folder"></i></div>
|
|
@@ -418,7 +418,7 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
|
|
| 418 |
|
| 419 |
const haptic = window.Telegram.WebApp.HapticFeedback;
|
| 420 |
|
| 421 |
-
async function openModal(srcOrUrl, type, itemId) {
|
| 422 |
if (!srcOrUrl) return;
|
| 423 |
haptic.impactOccurred('light');
|
| 424 |
const modal = document.getElementById('mediaModal');
|
|
@@ -429,7 +429,7 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
|
|
| 429 |
modal.style.display = 'flex';
|
| 430 |
|
| 431 |
if (type !== 'folder' && itemId) {
|
| 432 |
-
const downloadUrl = `{{
|
| 433 |
downloadBtn.onclick = () => { tmaDownloadFile(downloadUrl); };
|
| 434 |
downloadBtn.style.display = 'inline-block';
|
| 435 |
} else {
|
|
@@ -548,7 +548,13 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
|
|
| 548 |
function downloadSingleSelected() {
|
| 549 |
if (selectedItems.size !== 1) return;
|
| 550 |
const fileId = selectedItems.values().next().value;
|
| 551 |
-
const
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 552 |
tmaDownloadFile(url);
|
| 553 |
toggleSelectionMode(false);
|
| 554 |
}
|
|
@@ -720,32 +726,31 @@ def get_file_node_for_user(file_id):
|
|
| 720 |
return None
|
| 721 |
|
| 722 |
@app.route('/download_tma/<file_id>')
|
| 723 |
-
|
|
|
|
| 724 |
file_node = get_file_node_for_user(file_id)
|
| 725 |
if not file_node:
|
| 726 |
return Response("Файл не найден или доступ запрещен!", status=404)
|
| 727 |
-
|
| 728 |
hf_path = file_node.get('path')
|
| 729 |
original_filename = file_node.get('original_filename', 'downloaded_file')
|
| 730 |
if not hf_path:
|
| 731 |
return Response("Ошибка: Путь к файлу не найден.", status=500)
|
| 732 |
|
|
|
|
| 733 |
try:
|
| 734 |
-
|
| 735 |
-
|
| 736 |
-
|
| 737 |
-
|
| 738 |
-
|
| 739 |
-
|
| 740 |
-
|
| 741 |
-
)
|
| 742 |
-
|
| 743 |
-
|
| 744 |
-
as_attachment=True,
|
| 745 |
-
download_name=original_filename
|
| 746 |
-
)
|
| 747 |
except Exception as e:
|
| 748 |
-
logging.error(f"Error downloading {file_id} from HF
|
| 749 |
return Response(f'Ошибка скачивания файла: {e}', status=502)
|
| 750 |
|
| 751 |
@app.route('/batch_download_tma')
|
|
@@ -757,33 +762,30 @@ def batch_download_tma():
|
|
| 757 |
file_ids = file_ids_str.split(',')
|
| 758 |
|
| 759 |
temp_zip_file = tempfile.NamedTemporaryFile(delete=False, suffix=".zip")
|
|
|
|
|
|
|
| 760 |
|
| 761 |
try:
|
| 762 |
-
with zipfile.ZipFile(temp_zip_file
|
| 763 |
for file_id in file_ids:
|
| 764 |
file_node = get_file_node_for_user(file_id)
|
| 765 |
if file_node and file_node.get('path'):
|
| 766 |
hf_path = file_node['path']
|
| 767 |
original_filename = file_node.get('original_filename', file_id)
|
|
|
|
| 768 |
try:
|
| 769 |
-
|
| 770 |
-
|
| 771 |
-
|
| 772 |
-
repo_type="dataset",
|
| 773 |
-
token=HF_TOKEN_READ,
|
| 774 |
-
local_dir=UPLOAD_FOLDER,
|
| 775 |
-
local_dir_use_symlinks=False
|
| 776 |
-
)
|
| 777 |
-
zf.write(local_path, arcname=original_filename)
|
| 778 |
except Exception as e:
|
| 779 |
logging.error(f"Failed to download and add {original_filename} to zip: {e}")
|
| 780 |
|
|
|
|
| 781 |
return send_file(temp_zip_file.name, as_attachment=True, download_name='archive.zip', mimetype='application/zip')
|
| 782 |
finally:
|
| 783 |
if os.path.exists(temp_zip_file.name):
|
| 784 |
os.unlink(temp_zip_file.name)
|
| 785 |
|
| 786 |
-
|
| 787 |
@app.route('/delete_file_tma/<file_id>', methods=['POST'])
|
| 788 |
def delete_file_tma(file_id):
|
| 789 |
if 'telegram_user_id' not in session: return redirect(url_for('tma_entry_page'))
|
|
|
|
| 343 |
<div id="progress-container"><div id="progress-bar"></div></div>
|
| 344 |
<div class="file-grid" id="file-container">
|
| 345 |
{% for item in items %}
|
| 346 |
+
<div class="item {{ item.type }}" data-id="{{ item.id }}" data-type="{{ item.type }}" {% if item.type == 'file' %}data-filename="{{ item.original_filename }}"{% endif %} {% if item.type != 'folder' %}onclick="openModal('{{ hf_file_url_jinja(item.path) if item.file_type not in ['text', 'pdf'] else (url_for('get_text_content_tma', file_id=item.id) if item.file_type == 'text' else hf_file_url_jinja(item.path, True)) }}', '{{ item.file_type }}', '{{ item.id }}', {{ item.original_filename | tojson }})"{% else %}onclick="window.Telegram.WebApp.HapticFeedback.impactOccurred('light'); window.location.href='{{ url_for('tma_dashboard', folder_id=item.id) }}'"{% endif %}>
|
| 347 |
<div class="item-preview-wrapper">
|
| 348 |
{% if item.type == 'folder' %}
|
| 349 |
<div class="item-preview"><i class="fa-solid fa-folder"></i></div>
|
|
|
|
| 418 |
|
| 419 |
const haptic = window.Telegram.WebApp.HapticFeedback;
|
| 420 |
|
| 421 |
+
async function openModal(srcOrUrl, type, itemId, filename) {
|
| 422 |
if (!srcOrUrl) return;
|
| 423 |
haptic.impactOccurred('light');
|
| 424 |
const modal = document.getElementById('mediaModal');
|
|
|
|
| 429 |
modal.style.display = 'flex';
|
| 430 |
|
| 431 |
if (type !== 'folder' && itemId) {
|
| 432 |
+
const downloadUrl = `/download_tma/${itemId}/${encodeURIComponent(filename || 'download')}`;
|
| 433 |
downloadBtn.onclick = () => { tmaDownloadFile(downloadUrl); };
|
| 434 |
downloadBtn.style.display = 'inline-block';
|
| 435 |
} else {
|
|
|
|
| 548 |
function downloadSingleSelected() {
|
| 549 |
if (selectedItems.size !== 1) return;
|
| 550 |
const fileId = selectedItems.values().next().value;
|
| 551 |
+
const itemElement = document.querySelector(`.item[data-id='${fileId}']`);
|
| 552 |
+
if (!itemElement || !itemElement.dataset.filename) {
|
| 553 |
+
Telegram.WebApp.showAlert('Не удалось найти имя файла.');
|
| 554 |
+
return;
|
| 555 |
+
}
|
| 556 |
+
const filename = itemElement.dataset.filename;
|
| 557 |
+
const url = `/download_tma/${fileId}/${encodeURIComponent(filename)}`;
|
| 558 |
tmaDownloadFile(url);
|
| 559 |
toggleSelectionMode(false);
|
| 560 |
}
|
|
|
|
| 726 |
return None
|
| 727 |
|
| 728 |
@app.route('/download_tma/<file_id>')
|
| 729 |
+
@app.route('/download_tma/<file_id>/<path:filename>')
|
| 730 |
+
def download_tma(file_id, filename=None):
|
| 731 |
file_node = get_file_node_for_user(file_id)
|
| 732 |
if not file_node:
|
| 733 |
return Response("Файл не найден или доступ запрещен!", status=404)
|
| 734 |
+
|
| 735 |
hf_path = file_node.get('path')
|
| 736 |
original_filename = file_node.get('original_filename', 'downloaded_file')
|
| 737 |
if not hf_path:
|
| 738 |
return Response("Ошибка: Путь к файлу не найден.", status=500)
|
| 739 |
|
| 740 |
+
file_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{quote(hf_path)}?download=true"
|
| 741 |
try:
|
| 742 |
+
req_headers = {}
|
| 743 |
+
if HF_TOKEN_READ: req_headers["authorization"] = f"Bearer {HF_TOKEN_READ}"
|
| 744 |
+
r = requests.get(file_url, headers=req_headers, stream=True)
|
| 745 |
+
r.raise_for_status()
|
| 746 |
+
|
| 747 |
+
resp = Response(r.iter_content(chunk_size=8192), mimetype='application/octet-stream')
|
| 748 |
+
sanitized_filename = original_filename.replace('"', '_')
|
| 749 |
+
encoded_filename = quote(original_filename)
|
| 750 |
+
resp.headers['Content-Disposition'] = f"attachment; filename=\"{sanitized_filename}\"; filename*=UTF-8''{encoded_filename}"
|
| 751 |
+
return resp
|
|
|
|
|
|
|
|
|
|
| 752 |
except Exception as e:
|
| 753 |
+
logging.error(f"Error downloading {file_id} from HF: {e}")
|
| 754 |
return Response(f'Ошибка скачивания файла: {e}', status=502)
|
| 755 |
|
| 756 |
@app.route('/batch_download_tma')
|
|
|
|
| 762 |
file_ids = file_ids_str.split(',')
|
| 763 |
|
| 764 |
temp_zip_file = tempfile.NamedTemporaryFile(delete=False, suffix=".zip")
|
| 765 |
+
req_headers = {}
|
| 766 |
+
if HF_TOKEN_READ: req_headers["authorization"] = f"Bearer {HF_TOKEN_READ}"
|
| 767 |
|
| 768 |
try:
|
| 769 |
+
with zipfile.ZipFile(temp_zip_file, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 770 |
for file_id in file_ids:
|
| 771 |
file_node = get_file_node_for_user(file_id)
|
| 772 |
if file_node and file_node.get('path'):
|
| 773 |
hf_path = file_node['path']
|
| 774 |
original_filename = file_node.get('original_filename', file_id)
|
| 775 |
+
file_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{quote(hf_path)}?download=true"
|
| 776 |
try:
|
| 777 |
+
r = requests.get(file_url, headers=req_headers, stream=True)
|
| 778 |
+
r.raise_for_status()
|
| 779 |
+
zf.writestr(original_filename, r.content)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 780 |
except Exception as e:
|
| 781 |
logging.error(f"Failed to download and add {original_filename} to zip: {e}")
|
| 782 |
|
| 783 |
+
temp_zip_file.close()
|
| 784 |
return send_file(temp_zip_file.name, as_attachment=True, download_name='archive.zip', mimetype='application/zip')
|
| 785 |
finally:
|
| 786 |
if os.path.exists(temp_zip_file.name):
|
| 787 |
os.unlink(temp_zip_file.name)
|
| 788 |
|
|
|
|
| 789 |
@app.route('/delete_file_tma/<file_id>', methods=['POST'])
|
| 790 |
def delete_file_tma(file_id):
|
| 791 |
if 'telegram_user_id' not in session: return redirect(url_for('tma_entry_page'))
|