Implement CLI commands for batch extraction and PDF generation
- Added command-line interface using Click for `batch_extractor.py` to handle extraction from ZIP and PDF files. - Enhanced `save_to_excel` function to create parent directories for output files. - Updated `build_pdf.py` to include a CLI for generating PDF labels from Excel data. - Improved README.md with detailed usage instructions for the new CLI commands. - Added `click` to requirements.txt for command-line functionality.
This commit is contained in:
70
build_pdf.py
70
build_pdf.py
@@ -18,6 +18,9 @@ from read_image import read_datamatrix_zxing
|
||||
import render_eps
|
||||
import treepoem
|
||||
|
||||
import click
|
||||
from pathlib import Path
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# 1. СТРУКТУРЫ ДАННЫХ (DOMAIN LAYER)
|
||||
# ---------------------------------------------------------
|
||||
@@ -400,19 +403,56 @@ def process_batch(base64_codes: list[str], excel_path: str, output_dir: str):
|
||||
print(f" -> Сохранен файл: {pdf_path}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Тестовый пример оркестрации:
|
||||
base_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
image_path = "data/output.png"
|
||||
data = read_datamatrix_zxing(image_path)
|
||||
# Замените своими боевыми Base64 строками
|
||||
mock_base64_list = [
|
||||
read_datamatrix_zxing(image_path)[1],
|
||||
read_datamatrix_zxing(image_path)[1]
|
||||
]
|
||||
@click.command(help="Генерирует PDF-этикетки на основе извлеченных Base64-кодов и Excel-шаблона.")
|
||||
@click.argument('codes_xlsx', type=click.Path(exists=True, dir_okay=False, path_type=Path))
|
||||
@click.argument('template_xlsx', type=click.Path(exists=True, dir_okay=False, path_type=Path))
|
||||
@click.argument('output_dir', type=click.Path(file_okay=False, writable=True, path_type=Path))
|
||||
def cli(codes_xlsx: Path, template_xlsx: Path, output_dir: Path):
|
||||
"""
|
||||
Создает многостраничные PDF-файлы для термопринтера.
|
||||
|
||||
process_batch(
|
||||
base64_codes=mock_base64_list,
|
||||
excel_path=os.path.join(base_dir, "resources", "ШАблон для загрузки этикеток.xlsx"),
|
||||
output_dir=os.path.join(base_dir, "data", "output_pdfs")
|
||||
)
|
||||
CODES_XLSX: Путь к XLSX-файлу со списком кодов (структура: Текст / Base64).
|
||||
TEMPLATE_XLSX: Путь к XLSX-файлу с описанием товаров (GTIN, Артикул, Цвет и т.д.).
|
||||
OUTPUT_DIR: Папка, куда будут сохранены готовые PDF-файлы.
|
||||
"""
|
||||
click.echo(f"Подготовка к генерации PDF...")
|
||||
click.echo(f"Файл с кодами: {codes_xlsx.name}")
|
||||
click.echo(f"Файл шаблона: {template_xlsx.name}")
|
||||
|
||||
try:
|
||||
# 1. Читаем файл с извлеченными кодами
|
||||
codes_df = pd.read_excel(codes_xlsx, engine='openpyxl')
|
||||
|
||||
# Проверяем наличие нужной колонки
|
||||
if "Base64" not in codes_df.columns:
|
||||
click.secho("Ошибка: В файле кодов отсутствует колонка 'Base64'.", fg="red")
|
||||
return
|
||||
|
||||
# Извлекаем все коды в список строк
|
||||
base64_list = codes_df["Base64"].dropna().astype(str).tolist()
|
||||
|
||||
if not base64_list:
|
||||
click.secho("Предупреждение: Список Base64 кодов пуст.", fg="yellow")
|
||||
return
|
||||
|
||||
click.echo(f"Успешно загружено {len(base64_list)} кодов из {codes_xlsx.name}.")
|
||||
|
||||
# 2. Создаем выходную директорию (если её нет)
|
||||
# exist_ok=True предотвращает ошибку, если папка уже существует
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 3. Запускаем основной оркестратор
|
||||
# process_batch ожидает пути в виде строк (str), поэтому оборачиваем Path в str()
|
||||
process_batch(
|
||||
base64_codes=base64_list,
|
||||
excel_path=str(template_xlsx),
|
||||
output_dir=str(output_dir)
|
||||
)
|
||||
|
||||
click.secho(f"Генерация успешно завершена! Файлы сохранены в: {output_dir.absolute()}", fg="green")
|
||||
|
||||
except Exception as e:
|
||||
click.secho(f"Критическая ошибка при генерации PDF: {e}", fg="red")
|
||||
|
||||
if __name__ == "__main__":
|
||||
cli()
|
||||
Reference in New Issue
Block a user