cleaner.py i standarizer.py
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
# processors/converter.py
|
||||
|
||||
import os
|
||||
import zipfile
|
||||
import rarfile
|
||||
import tempfile
|
||||
import shutil
|
||||
|
||||
|
||||
def decide_target_format(original_path, desired_format="cbz"):
|
||||
"""
|
||||
Decide si el archivo debe convertirse y cuál será su ruta final.
|
||||
No realiza la conversión.
|
||||
"""
|
||||
base, _ = os.path.splitext(original_path)
|
||||
target_path = f"{base}.{desired_format.lower()}"
|
||||
|
||||
needs_conversion = not original_path.lower().endswith(desired_format.lower())
|
||||
|
||||
return {
|
||||
"needs_conversion": needs_conversion,
|
||||
"target_format": desired_format.lower(),
|
||||
"target_path": target_path
|
||||
}
|
||||
|
||||
|
||||
def convert_comic(path, desired_format="cbz"):
|
||||
"""
|
||||
Convierte un archivo CBR/CBZ al formato deseado.
|
||||
NO limpia basura.
|
||||
NO renombra páginas.
|
||||
NO reordena nada.
|
||||
"""
|
||||
info = decide_target_format(path, desired_format)
|
||||
|
||||
if not info["needs_conversion"]:
|
||||
return info # Nada que hacer
|
||||
|
||||
ext = os.path.splitext(path)[1].lower()
|
||||
|
||||
# 1) Abrir archivo original
|
||||
if ext == ".cbr":
|
||||
archive = rarfile.RarFile(path, "r")
|
||||
elif ext == ".cbz":
|
||||
archive = zipfile.ZipFile(path, "r")
|
||||
else:
|
||||
raise Exception("Formato no soportado")
|
||||
|
||||
# 2) Extraer a carpeta temporal
|
||||
temp_dir = tempfile.mkdtemp()
|
||||
archive.extractall(temp_dir)
|
||||
archive.close()
|
||||
|
||||
# 3) Reempaquetar en el formato deseado
|
||||
target_path = info["target_path"]
|
||||
|
||||
if desired_format == "cbz":
|
||||
with zipfile.ZipFile(target_path, "w", zipfile.ZIP_DEFLATED) as new_zip:
|
||||
for root, _, files in os.walk(temp_dir):
|
||||
for f in files:
|
||||
full = os.path.join(root, f)
|
||||
rel = os.path.relpath(full, temp_dir)
|
||||
new_zip.write(full, rel)
|
||||
|
||||
elif desired_format == "cbr":
|
||||
# rarfile no puede crear RAR → hay que usar "rar" externo
|
||||
raise NotImplementedError("Crear CBR requiere la herramienta 'rar' instalada")
|
||||
|
||||
# 4) Limpiar temporal
|
||||
shutil.rmtree(temp_dir)
|
||||
|
||||
return info
|
||||
Reference in New Issue
Block a user