Spaces:
Running
Running
deploy from github actions
Browse files- app/utils/hf_storage.py +40 -2
- tasks.py +70 -53
app/utils/hf_storage.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
import os
|
| 2 |
import logging
|
| 3 |
-
from huggingface_hub import HfApi
|
| 4 |
|
| 5 |
logger = logging.getLogger(__name__)
|
| 6 |
|
|
@@ -39,6 +39,44 @@ def upload_to_hf(file_path: str, object_name: str) -> str:
|
|
| 39 |
logger.error(f"Error subiendo archivo {object_name} a Hugging Face: {e}")
|
| 40 |
raise e
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
def delete_from_hf(object_name: str):
|
| 43 |
"""
|
| 44 |
Elimina un archivo del dataset de Hugging Face.
|
|
@@ -72,7 +110,7 @@ def delete_folder_from_hf(prefix: str):
|
|
| 72 |
|
| 73 |
try:
|
| 74 |
api.delete_folder(
|
| 75 |
-
|
| 76 |
repo_id=HF_STORAGE_REPO,
|
| 77 |
repo_type="dataset"
|
| 78 |
)
|
|
|
|
| 1 |
import os
|
| 2 |
import logging
|
| 3 |
+
from huggingface_hub import HfApi, CommitOperationAdd
|
| 4 |
|
| 5 |
logger = logging.getLogger(__name__)
|
| 6 |
|
|
|
|
| 39 |
logger.error(f"Error subiendo archivo {object_name} a Hugging Face: {e}")
|
| 40 |
raise e
|
| 41 |
|
| 42 |
+
def upload_many_to_hf(files, commit_message: str = "Subir archivos") -> dict:
|
| 43 |
+
"""
|
| 44 |
+
Sube varios archivos en UN solo commit (el dataset tiene un límite de commits por hora,
|
| 45 |
+
y subir archivo por archivo lo agota con pocas canciones).
|
| 46 |
+
files: lista de (ruta_local, object_name). Retorna {object_name: url_publica} de los subidos.
|
| 47 |
+
Si el commit conjunto falla, reintenta archivo por archivo para no perder los que sí suben.
|
| 48 |
+
"""
|
| 49 |
+
files = [(path, name) for path, name in files if os.path.exists(path)]
|
| 50 |
+
if not files:
|
| 51 |
+
return {}
|
| 52 |
+
|
| 53 |
+
api = get_hf_api()
|
| 54 |
+
if not api:
|
| 55 |
+
raise RuntimeError(
|
| 56 |
+
f"HF_TOKEN no está configurado en las variables de entorno. "
|
| 57 |
+
f"No se pueden subir archivos a Hugging Face Dataset '{HF_STORAGE_REPO}'."
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
try:
|
| 61 |
+
api.create_commit(
|
| 62 |
+
repo_id=HF_STORAGE_REPO,
|
| 63 |
+
repo_type="dataset",
|
| 64 |
+
operations=[CommitOperationAdd(path_in_repo=name, path_or_fileobj=path) for path, name in files],
|
| 65 |
+
commit_message=commit_message
|
| 66 |
+
)
|
| 67 |
+
logger.info(f"{len(files)} archivos subidos a Hugging Face Dataset en un solo commit: {commit_message}")
|
| 68 |
+
return {name: get_hf_download_url(name) for _, name in files}
|
| 69 |
+
except Exception as e:
|
| 70 |
+
logger.warning(f"Falló el commit conjunto ({commit_message}): {e}. Reintentando archivo por archivo...")
|
| 71 |
+
|
| 72 |
+
urls = {}
|
| 73 |
+
for path, name in files:
|
| 74 |
+
try:
|
| 75 |
+
urls[name] = upload_to_hf(path, name)
|
| 76 |
+
except Exception as e:
|
| 77 |
+
logger.error(f"Error subiendo {name} a Hugging Face: {e}")
|
| 78 |
+
return urls
|
| 79 |
+
|
| 80 |
def delete_from_hf(object_name: str):
|
| 81 |
"""
|
| 82 |
Elimina un archivo del dataset de Hugging Face.
|
|
|
|
| 110 |
|
| 111 |
try:
|
| 112 |
api.delete_folder(
|
| 113 |
+
path_in_repo=prefix,
|
| 114 |
repo_id=HF_STORAGE_REPO,
|
| 115 |
repo_type="dataset"
|
| 116 |
)
|
tasks.py
CHANGED
|
@@ -1669,25 +1669,31 @@ def procesar_cancion_completa(self, file_path, task_id, stems, trim_start="", tr
|
|
| 1669 |
|
| 1670 |
hf_urls = {}
|
| 1671 |
failed_stems = []
|
| 1672 |
-
from app.utils.hf_storage import
|
| 1673 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1674 |
for stem_name, stem_path, ext in stems_to_upload:
|
| 1675 |
-
|
| 1676 |
-
|
| 1677 |
-
|
| 1678 |
-
|
| 1679 |
-
object_name = f"stems/{task_id}/{stem_name}.{ext}"
|
| 1680 |
-
public_url = upload_to_hf(stem_path, object_name)
|
| 1681 |
-
hf_urls[stem_name] = public_url
|
| 1682 |
logger.info(f"[{task_id}] Stem '{stem_name}' subido exitosamente a HF.")
|
| 1683 |
-
|
| 1684 |
# Solo eliminar del disco si la subida fue exitosa
|
| 1685 |
if os.path.exists(stem_path):
|
| 1686 |
os.remove(stem_path)
|
| 1687 |
-
|
| 1688 |
-
|
| 1689 |
-
except Exception as stem_err:
|
| 1690 |
-
logger.error(f"[{task_id}] Fallo al subir '{stem_name}' a Hugging Face: {stem_err}")
|
| 1691 |
failed_stems.append(stem_name)
|
| 1692 |
# NO eliminar el archivo local — queda para diagnóstico
|
| 1693 |
|
|
@@ -1746,32 +1752,34 @@ def procesar_cancion_completa(self, file_path, task_id, stems, trim_start="", tr
|
|
| 1746 |
"3ra_voz_pitch.json", "3ra_voz_baja_pitch.json", "oct_alta_pitch.json", "oct_baja_pitch.json"
|
| 1747 |
]
|
| 1748 |
|
|
|
|
|
|
|
| 1749 |
for _v in _voces:
|
| 1750 |
for _vext in ['m4a', 'flac']:
|
| 1751 |
_vpath = os.path.join(_song_dir, f"{_v}.{_vext}")
|
| 1752 |
if os.path.exists(_vpath):
|
| 1753 |
-
|
| 1754 |
-
try:
|
| 1755 |
-
_pub_url = upload_to_hf(_vpath, _obj_key)
|
| 1756 |
-
harmony_urls[_v] = _pub_url
|
| 1757 |
-
hf_urls[_v] = _pub_url
|
| 1758 |
-
os.remove(_vpath)
|
| 1759 |
-
except Exception as _ve:
|
| 1760 |
-
logger.warning(f"[{task_id}] Error subiendo voz coral {_v}: {_ve}")
|
| 1761 |
break
|
| 1762 |
-
|
| 1763 |
for _pj in _pitch_jsons:
|
| 1764 |
_pj_path = os.path.join(_song_dir, _pj)
|
| 1765 |
if os.path.exists(_pj_path):
|
| 1766 |
-
|
| 1767 |
-
|
| 1768 |
-
|
| 1769 |
-
|
| 1770 |
-
|
| 1771 |
-
|
| 1772 |
-
|
| 1773 |
-
|
| 1774 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1775 |
|
| 1776 |
# Limpiar vocals descargado si lo trajimos de HF
|
| 1777 |
try:
|
|
@@ -2083,7 +2091,7 @@ def generar_armonias_task(self, task_id: str):
|
|
| 2083 |
from app.models.process import Task as TaskModel
|
| 2084 |
from app.utils.redis_client import get_redis_client
|
| 2085 |
from app.utils.harmony import generar_armonias
|
| 2086 |
-
from app.utils.hf_storage import
|
| 2087 |
import json
|
| 2088 |
import os
|
| 2089 |
import shutil
|
|
@@ -2179,28 +2187,29 @@ def generar_armonias_task(self, task_id: str):
|
|
| 2179 |
"3ra_voz_pitch.json", "3ra_voz_baja_pitch.json", "oct_alta_pitch.json", "oct_baja_pitch.json"
|
| 2180 |
]
|
| 2181 |
|
| 2182 |
-
|
| 2183 |
-
|
| 2184 |
for v in voces_corales:
|
| 2185 |
file_path = os.path.join(song_dir, f"{v}.m4a")
|
| 2186 |
ext = "m4a"
|
| 2187 |
if not os.path.exists(file_path):
|
| 2188 |
file_path = os.path.join(song_dir, f"{v}.flac")
|
| 2189 |
ext = "flac"
|
| 2190 |
-
|
| 2191 |
if os.path.exists(file_path):
|
| 2192 |
-
|
| 2193 |
-
public_url = upload_to_hf(file_path, object_key)
|
| 2194 |
-
uploaded_files[v] = public_url
|
| 2195 |
-
|
| 2196 |
-
# Subir jsons
|
| 2197 |
for pj in pitch_jsons:
|
| 2198 |
file_path = os.path.join(song_dir, pj)
|
| 2199 |
if os.path.exists(file_path):
|
| 2200 |
-
|
| 2201 |
-
|
| 2202 |
-
|
| 2203 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2204 |
|
| 2205 |
# 4. Actualizar base de datos
|
| 2206 |
from datetime import timedelta
|
|
@@ -2407,27 +2416,35 @@ def aplicar_recarga_mensual_creditos_task():
|
|
| 2407 |
def sync_local_task_to_cloud(task_id, stems_to_upload, acordes, stems, user_id, song_name, artist):
|
| 2408 |
logger.info(f"[{task_id}] Iniciando sincronización de respaldo a la nube en background (desde backup)...")
|
| 2409 |
try:
|
| 2410 |
-
from app.utils.hf_storage import
|
| 2411 |
from app.database import SessionLocal
|
| 2412 |
from app.models.process import Task as TaskModel
|
| 2413 |
import json
|
| 2414 |
from datetime import datetime
|
| 2415 |
-
|
| 2416 |
hf_urls = {}
|
| 2417 |
failed_stems = []
|
|
|
|
| 2418 |
for stem_name, stem_path, ext in stems_to_upload:
|
| 2419 |
if not os.path.exists(stem_path):
|
| 2420 |
logger.warning(f"[{task_id}] Archivo de backup {stem_path} no existe.")
|
| 2421 |
continue
|
| 2422 |
-
|
| 2423 |
-
|
| 2424 |
-
|
| 2425 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2426 |
logger.info(f"[{task_id}] Respaldado stem '{stem_name}' a HF.")
|
| 2427 |
# Eliminar archivo de backup individual
|
| 2428 |
os.remove(stem_path)
|
| 2429 |
-
|
| 2430 |
-
logger.error(f"[{task_id}] Error respaldando stem '{stem_name}'
|
| 2431 |
failed_stems.append(stem_name)
|
| 2432 |
|
| 2433 |
if hf_urls:
|
|
|
|
| 1669 |
|
| 1670 |
hf_urls = {}
|
| 1671 |
failed_stems = []
|
| 1672 |
+
from app.utils.hf_storage import upload_many_to_hf, HF_STORAGE_REPO
|
| 1673 |
+
|
| 1674 |
+
if not check_task_still_exists(task_id):
|
| 1675 |
+
raise TaskCancelledException("Tarea cancelada por el usuario.")
|
| 1676 |
+
|
| 1677 |
+
# Todos los stems en un solo commit (límite de commits por hora del dataset)
|
| 1678 |
+
try:
|
| 1679 |
+
uploaded = upload_many_to_hf(
|
| 1680 |
+
[(stem_path, f"stems/{task_id}/{stem_name}.{ext}") for stem_name, stem_path, ext in stems_to_upload],
|
| 1681 |
+
commit_message=f"Stems de {task_id}"
|
| 1682 |
+
)
|
| 1683 |
+
except Exception as upload_err:
|
| 1684 |
+
logger.error(f"[{task_id}] Fallo al subir los stems a Hugging Face: {upload_err}")
|
| 1685 |
+
uploaded = {}
|
| 1686 |
+
|
| 1687 |
for stem_name, stem_path, ext in stems_to_upload:
|
| 1688 |
+
object_name = f"stems/{task_id}/{stem_name}.{ext}"
|
| 1689 |
+
if object_name in uploaded:
|
| 1690 |
+
hf_urls[stem_name] = uploaded[object_name]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1691 |
logger.info(f"[{task_id}] Stem '{stem_name}' subido exitosamente a HF.")
|
|
|
|
| 1692 |
# Solo eliminar del disco si la subida fue exitosa
|
| 1693 |
if os.path.exists(stem_path):
|
| 1694 |
os.remove(stem_path)
|
| 1695 |
+
else:
|
| 1696 |
+
logger.error(f"[{task_id}] Fallo al subir '{stem_name}' a Hugging Face.")
|
|
|
|
|
|
|
| 1697 |
failed_stems.append(stem_name)
|
| 1698 |
# NO eliminar el archivo local — queda para diagnóstico
|
| 1699 |
|
|
|
|
| 1752 |
"3ra_voz_pitch.json", "3ra_voz_baja_pitch.json", "oct_alta_pitch.json", "oct_baja_pitch.json"
|
| 1753 |
]
|
| 1754 |
|
| 1755 |
+
# (clave, ruta local, object_name) de voces y pitch JSON, subidos en un solo commit
|
| 1756 |
+
_harmony_files = []
|
| 1757 |
for _v in _voces:
|
| 1758 |
for _vext in ['m4a', 'flac']:
|
| 1759 |
_vpath = os.path.join(_song_dir, f"{_v}.{_vext}")
|
| 1760 |
if os.path.exists(_vpath):
|
| 1761 |
+
_harmony_files.append((_v, _vpath, f"stems/{task_id}/{_v}.{_vext}"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1762 |
break
|
|
|
|
| 1763 |
for _pj in _pitch_jsons:
|
| 1764 |
_pj_path = os.path.join(_song_dir, _pj)
|
| 1765 |
if os.path.exists(_pj_path):
|
| 1766 |
+
_harmony_files.append((_pj.replace(".json", ""), _pj_path, f"stems/{task_id}/{_pj}"))
|
| 1767 |
+
|
| 1768 |
+
try:
|
| 1769 |
+
_uploaded = upload_many_to_hf(
|
| 1770 |
+
[(_path, _key) for _, _path, _key in _harmony_files],
|
| 1771 |
+
commit_message=f"Voces corales de {task_id}"
|
| 1772 |
+
)
|
| 1773 |
+
except Exception as _he:
|
| 1774 |
+
logger.warning(f"[{task_id}] Error subiendo voces corales: {_he}")
|
| 1775 |
+
_uploaded = {}
|
| 1776 |
+
for _hk, _path, _key in _harmony_files:
|
| 1777 |
+
if _key in _uploaded:
|
| 1778 |
+
harmony_urls[_hk] = _uploaded[_key]
|
| 1779 |
+
hf_urls[_hk] = _uploaded[_key]
|
| 1780 |
+
os.remove(_path)
|
| 1781 |
+
else:
|
| 1782 |
+
logger.warning(f"[{task_id}] Error subiendo {_key}")
|
| 1783 |
|
| 1784 |
# Limpiar vocals descargado si lo trajimos de HF
|
| 1785 |
try:
|
|
|
|
| 2091 |
from app.models.process import Task as TaskModel
|
| 2092 |
from app.utils.redis_client import get_redis_client
|
| 2093 |
from app.utils.harmony import generar_armonias
|
| 2094 |
+
from app.utils.hf_storage import upload_many_to_hf, get_hf_download_url
|
| 2095 |
import json
|
| 2096 |
import os
|
| 2097 |
import shutil
|
|
|
|
| 2187 |
"3ra_voz_pitch.json", "3ra_voz_baja_pitch.json", "oct_alta_pitch.json", "oct_baja_pitch.json"
|
| 2188 |
]
|
| 2189 |
|
| 2190 |
+
# (clave, ruta local, object_name) de audios corales y jsons, subidos en un solo commit
|
| 2191 |
+
harmony_files = []
|
| 2192 |
for v in voces_corales:
|
| 2193 |
file_path = os.path.join(song_dir, f"{v}.m4a")
|
| 2194 |
ext = "m4a"
|
| 2195 |
if not os.path.exists(file_path):
|
| 2196 |
file_path = os.path.join(song_dir, f"{v}.flac")
|
| 2197 |
ext = "flac"
|
|
|
|
| 2198 |
if os.path.exists(file_path):
|
| 2199 |
+
harmony_files.append((v, file_path, f"stems/{task_id}/{v}.{ext}"))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2200 |
for pj in pitch_jsons:
|
| 2201 |
file_path = os.path.join(song_dir, pj)
|
| 2202 |
if os.path.exists(file_path):
|
| 2203 |
+
harmony_files.append((pj.replace(".json", ""), file_path, f"stems/{task_id}/{pj}"))
|
| 2204 |
+
|
| 2205 |
+
uploaded = upload_many_to_hf(
|
| 2206 |
+
[(path, key) for _, path, key in harmony_files],
|
| 2207 |
+
commit_message=f"Voces corales de {task_id}"
|
| 2208 |
+
)
|
| 2209 |
+
missing = [key for _, _, key in harmony_files if key not in uploaded]
|
| 2210 |
+
if missing:
|
| 2211 |
+
raise RuntimeError(f"No se pudieron subir a Hugging Face: {missing}")
|
| 2212 |
+
uploaded_files = {name: uploaded[key] for name, _, key in harmony_files}
|
| 2213 |
|
| 2214 |
# 4. Actualizar base de datos
|
| 2215 |
from datetime import timedelta
|
|
|
|
| 2416 |
def sync_local_task_to_cloud(task_id, stems_to_upload, acordes, stems, user_id, song_name, artist):
|
| 2417 |
logger.info(f"[{task_id}] Iniciando sincronización de respaldo a la nube en background (desde backup)...")
|
| 2418 |
try:
|
| 2419 |
+
from app.utils.hf_storage import upload_many_to_hf
|
| 2420 |
from app.database import SessionLocal
|
| 2421 |
from app.models.process import Task as TaskModel
|
| 2422 |
import json
|
| 2423 |
from datetime import datetime
|
| 2424 |
+
|
| 2425 |
hf_urls = {}
|
| 2426 |
failed_stems = []
|
| 2427 |
+
existing = []
|
| 2428 |
for stem_name, stem_path, ext in stems_to_upload:
|
| 2429 |
if not os.path.exists(stem_path):
|
| 2430 |
logger.warning(f"[{task_id}] Archivo de backup {stem_path} no existe.")
|
| 2431 |
continue
|
| 2432 |
+
existing.append((stem_name, stem_path, f"stems/{task_id}/{stem_name}.{ext}"))
|
| 2433 |
+
|
| 2434 |
+
# Todos los stems del respaldo en un solo commit
|
| 2435 |
+
try:
|
| 2436 |
+
uploaded = upload_many_to_hf([(path, key) for _, path, key in existing], commit_message=f"Respaldo de {task_id}")
|
| 2437 |
+
except Exception as e:
|
| 2438 |
+
logger.error(f"[{task_id}] Error respaldando stems: {e}")
|
| 2439 |
+
uploaded = {}
|
| 2440 |
+
for stem_name, stem_path, object_name in existing:
|
| 2441 |
+
if object_name in uploaded:
|
| 2442 |
+
hf_urls[stem_name] = uploaded[object_name]
|
| 2443 |
logger.info(f"[{task_id}] Respaldado stem '{stem_name}' a HF.")
|
| 2444 |
# Eliminar archivo de backup individual
|
| 2445 |
os.remove(stem_path)
|
| 2446 |
+
else:
|
| 2447 |
+
logger.error(f"[{task_id}] Error respaldando stem '{stem_name}'.")
|
| 2448 |
failed_stems.append(stem_name)
|
| 2449 |
|
| 2450 |
if hf_urls:
|