Eluza133 commited on
Commit
f7b28f3
·
verified ·
1 Parent(s): 48a43b7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -33
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 == '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,7 +418,7 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
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,7 +429,7 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
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,13 +548,7 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
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,8 +720,7 @@ def get_file_node_for_user(file_id):
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)
@@ -737,20 +730,24 @@ def download_tma(file_id, filename=None):
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,30 +759,32 @@ def 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'))
 
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
 
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
  modal.style.display = 'flex';
430
 
431
  if (type !== 'folder' && itemId) {
432
+ const downloadUrl = `{{ url_for('download_tma', file_id='__FILE_ID__') }}`.replace('__FILE_ID__', itemId);
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 url = `{{ url_for("download_tma", file_id='__FILE_ID__') }}`.replace('__FILE_ID__', fileId);
 
 
 
 
 
 
552
  tmaDownloadFile(url);
553
  toggleSelectionMode(false);
554
  }
 
720
  return None
721
 
722
  @app.route('/download_tma/<file_id>')
723
+ def download_tma(file_id):
 
724
  file_node = get_file_node_for_user(file_id)
725
  if not file_node:
726
  return Response("Файл не найден или доступ запрещен!", status=404)
 
730
  if not hf_path:
731
  return Response("Ошибка: Путь к файлу не найден.", status=500)
732
 
 
733
  try:
734
+ local_file_path = hf_hub_download(
735
+ repo_id=REPO_ID,
736
+ filename=hf_path,
737
+ repo_type="dataset",
738
+ token=HF_TOKEN_READ,
739
+ cache_dir=os.path.join(UPLOAD_FOLDER, 'hf_download_cache')
740
+ )
741
+ return send_file(
742
+ local_file_path,
743
+ as_attachment=True,
744
+ download_name=original_filename
745
+ )
746
+ except hf_utils.EntryNotFoundError:
747
+ logging.error(f"File not found on Hugging Face: {hf_path}")
748
+ return Response("Файл не найден на удаленном хранилище.", status=404)
749
  except Exception as e:
750
+ logging.error(f"Error downloading {file_id} from HF via hf_hub_download: {e}")
751
  return Response(f'Ошибка скачивания файла: {e}', status=502)
752
 
753
  @app.route('/batch_download_tma')
 
759
  file_ids = file_ids_str.split(',')
760
 
761
  temp_zip_file = tempfile.NamedTemporaryFile(delete=False, suffix=".zip")
762
+
 
 
763
  try:
764
+ with zipfile.ZipFile(temp_zip_file.name, 'w', zipfile.ZIP_DEFLATED) as zf:
765
  for file_id in file_ids:
766
  file_node = get_file_node_for_user(file_id)
767
  if file_node and file_node.get('path'):
768
  hf_path = file_node['path']
769
  original_filename = file_node.get('original_filename', file_id)
 
770
  try:
771
+ local_file_path = hf_hub_download(
772
+ repo_id=REPO_ID,
773
+ filename=hf_path,
774
+ repo_type="dataset",
775
+ token=HF_TOKEN_READ,
776
+ cache_dir=os.path.join(UPLOAD_FOLDER, 'hf_download_cache')
777
+ )
778
+ zf.write(local_file_path, arcname=original_filename)
779
  except Exception as e:
780
  logging.error(f"Failed to download and add {original_filename} to zip: {e}")
781
 
 
782
  return send_file(temp_zip_file.name, as_attachment=True, download_name='archive.zip', mimetype='application/zip')
783
  finally:
784
  if os.path.exists(temp_zip_file.name):
785
  os.unlink(temp_zip_file.name)
786
 
787
+
788
  @app.route('/delete_file_tma/<file_id>', methods=['POST'])
789
  def delete_file_tma(file_id):
790
  if 'telegram_user_id' not in session: return redirect(url_for('tma_entry_page'))