Refactor barcode extraction and enhance PDF processing capabilities
- Added extract_barcodes_from_pdf function to read barcodes from PDF files using fitz. - Updated read_datamatrix_zxing to return both the barcode text and its Base64 representation. - Modified main execution block to include PDF barcode extraction. - Improved image loading for better compatibility with zxing. - Updated requirements.txt to include pymupdf for PDF processing.
This commit is contained in:
@@ -1,18 +1,53 @@
|
||||
import zxingcpp as zxing_cpp
|
||||
from PIL import Image
|
||||
import base64
|
||||
import fitz
|
||||
|
||||
def read_datamatrix_zxing(file_path: str) -> str:
|
||||
# Открываем изображение через Pillow
|
||||
img = Image.open(file_path)
|
||||
|
||||
def extract_barcodes_from_pdf(pdf_path: str):
|
||||
results = []
|
||||
|
||||
# Читаем штрих-код.
|
||||
# zxing_cpp.read_barcodes умеет работать напрямую с объектами PIL
|
||||
results = zxing_cpp.read_barcodes(img)
|
||||
doc = fitz.open(pdf_path)
|
||||
|
||||
for page_num in range(len(doc)):
|
||||
page = doc[page_num]
|
||||
|
||||
matrix = fitz.Matrix(2.0, 2.0)
|
||||
pix = page.get_pixmap(matrix=matrix)
|
||||
|
||||
img = Image.frombytes(mode="RGB", size=(pix.width, pix.height), data=pix.samples)
|
||||
|
||||
barcodes = zxing_cpp.read_barcodes(img)
|
||||
|
||||
for barcode in barcodes:
|
||||
b64_string = base64.b64encode(barcode.bytes).decode('ascii')
|
||||
results.append({
|
||||
"page": page_num + 1,
|
||||
"text": barcode.text,
|
||||
"base64": b64_string,
|
||||
"format": barcode.format.name
|
||||
})
|
||||
|
||||
doc.close()
|
||||
return results
|
||||
|
||||
def read_datamatrix_zxing(file_path: str) -> tuple[str, str]:
|
||||
# Открываем изображение через Pillow
|
||||
with Image.open(file_path) as img:
|
||||
img.load(scale=10)
|
||||
# Для EPS файлов (и других специфичных форматов) Pillow загружает данные "лениво".
|
||||
# Чтобы избежать ошибки "does not support the buffer protocol" в zxing,
|
||||
# нам нужно принудительно загрузить данные и конвертировать их в понятный цветовой режим,
|
||||
# например, в 'L' (оттенки серого) или 'RGB', который zxing гарантированно поддерживает.
|
||||
img = img.convert("RGB")
|
||||
|
||||
# Читаем штрих-код.
|
||||
# zxing_cpp.read_barcodes умеет работать напрямую с объектами PIL
|
||||
results = zxing_cpp.read_barcodes(img)
|
||||
|
||||
if not results:
|
||||
print("Коды не найдены на изображении.")
|
||||
return ''
|
||||
return ('','')
|
||||
|
||||
# Берем первый найденный код
|
||||
result = results[0]
|
||||
@@ -24,11 +59,13 @@ def read_datamatrix_zxing(file_path: str) -> str:
|
||||
# b64encode возвращает bytes, поэтому делаем .decode('ascii') для получения строки
|
||||
b64_string = base64.b64encode(raw_bytes).decode('ascii')
|
||||
|
||||
return b64_string
|
||||
return (result.text, b64_string)
|
||||
|
||||
if __name__ == "__main__":
|
||||
image_path = "data/output.png"
|
||||
data = read_datamatrix_zxing(image_path)
|
||||
text, data = read_datamatrix_zxing(image_path)
|
||||
pdf_read_path = 'data/output_pdfs/Labels_04639970975115.pdf'
|
||||
results = extract_barcodes_from_pdf(pdf_read_path)
|
||||
|
||||
if data:
|
||||
print(f"Успешно прочитано: {data}")
|
||||
|
||||
Reference in New Issue
Block a user