Перепиши в утилиту командной строки на баш с прогрессбаром, поддерржкой пдф и djvu png jpg
Assistant
User
File "/tmp/tmp.RENtgCvjct/ocr.py", line 2, in
from shiftlab_ocr.doc2text import Reader
ImportError: cannot import name 'Reader' from 'shiftlab_ocr.doc2text'
Assistant
User
./doc2text.sh: line 6: /ocr.py: Permission denied
./doc2text.sh: line 53: Также: command not found
Assistant
User
RuntimeError: operator torchvision::nms does not exist
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Based on the provided repository code, I'll help create a bash script that converts various document formats (PDF, DJVU, JPG, PNG) to text using the shiftlab_ocr library, adding a progress bar and command line interface.
Here's the bash script:
bash
#!/bin/bash
# Check dependencies
command -v pdfimages >/dev/null 2>&1 || { echo "Please install poppler-utils (pdfimages)"; exit 1; }
command -v ddjvu >/dev/null 2>&1 || { echo "Please install djvulibre-bin"; exit 1; }
command -v python3 >/dev/null 2>&1 || { echo "Please install python3"; exit 1; }
# Help message
show_help() {
echo "Usage: $0 [-i INPUT_FILE] [-o OUTPUT_FILE]"
echo "Convert PDF/DJVU/PNG/JPG documents to text"
echo ""
echo "Options:"
echo " -i Input file (PDF, DJVU, PNG or JPG)"
echo " -o Output text file (default: output.txt)"
exit 1
}
# Parse arguments
while getopts "i:o:h" opt; do
case $opt in
i) input="$OPTARG";;
o) output="${OPTARG:-output.txt}";;
h) show_help;;
\?) show_help;;
esac
done
if [ -z "$input" ]; then
show_help
fi
# Create temporary directory
temp_dir=$(mktemp -d)
trap 'rm -rf "$temp_dir"' EXIT
# Python script for OCR
cat > "$temp_dir/ocr.py" << 'EOF'
import sys
from shiftlab_ocr.doc2text import Reader
from tqdm import tqdm
reader = Reader()
input_file = sys.argv[1]
output_file = sys.argv[2]
text, _ = reader.doc2text(input_file)
with open(output_file, 'a', encoding='utf-8') as f:
f.write(text + '\n')
EOF
# Function to process images
process_images() {
local total=$(ls "$temp_dir"/*.{png,jpg} 2>/dev/null | wc -l)
local counter=0
for img in "$temp_dir"/*.{png,jpg}; do
[ -e "$img" ] || continue
# Progress bar
counter=$((counter + 1))
printf "Processing image %d/%d\r" "$counter" "$total"
python3 "$temp_dir/ocr.py" "$img" "$output"
done
echo ""
}
# Process based on file extension
case "${input,,}" in
*.pdf)
echo "Converting PDF to images..."
pdfimages -png "$input" "$temp_dir/page"
process_images
;;
*.djvu)
echo "Converting DJVU to images..."
ddjvu -format=png -mode=black -page=1- "$input" "$temp_dir/page_%d.png"
process_images
;;
*.png|*.jpg|*.jpeg)
cp "$input" "$temp_dir/page.png"
process_images
;;
*)
echo "Unsupported file format"
exit 1
;;
esac
echo "Text saved to: $output"
Автоматически конвертирует PDF и DJVU в изображения
Использует временную директорию для промежуточных файлов
Обрабатывает многостраничные документы
Сохраняет результат в указанный текстовый файл
Все распознанные тексты будут сохранены в выходной файл в кодировке UTF-8.
Извините за ошибку. Судя по структуре репозитория, нужно скорректировать импорты. Вот исправленная версия Python-скрипта для OCR:
bash
#!/bin/bash
# ... (предыдущий код без изменений до места с Python скриптом)
# Python script for OCR
cat > "$temp_dir/ocr.py" << 'EOF'
import sys
from shiftlab_ocr.doc2text.reader import Reader
from tqdm import tqdm
import os
# Ensure the weights directory exists in the same location as the script
script_dir = os.path.dirname(os.path.abspath(__file__))
weights_dir = os.path.join(script_dir, "weights")
os.makedirs(weights_dir, exist_ok=True)
# Initialize reader with explicit paths
reader = Reader(
yolo_path=os.path.join(script_dir, "yolov5"),
detector_weights=os.path.join(weights_dir, "weights.pt"),
recognizer_weights=os.path.join(weights_dir, "ocr_transformer_4h2l_simple_conv_64x256.pt")
)
def process_image(input_file, output_file):
try:
text, _ = reader.doc2text(input_file)
with open(output_file, 'a', encoding='utf-8') as f:
f.write(text + '\n')
return True
except Exception as e:
print(f"Error processing {input_file}: {str(e)}")
return False
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python ocr.py input_file output_file")
sys.exit(1)
input_file = sys.argv[1]
output_file = sys.argv[2]
if not os.path.exists(input_file):
print(f"Input file {input_file} does not exist")
sys.exit(1)
success = process_image(input_file, output_file)
if not success:
sys.exit(1)
EOF
# ... (остальной код без изменений)
Также нужно убедиться, что все необходимые веса моделей установлены. Добавьте следующий код перед основным скриптом для проверки и скачивания весов:
Скачайте и установите веса моделей в директорию $HOME/.shiftlab_ocr/weights/:
weights.pt
ocr_transformer_4h2l_simple_conv_64x256.pt
Запустите скрипт:
bash
./doc2text.sh -i input.pdf -o output.txt
Обратите внимание, что для работы скрипта необходимо иметь файлы весов моделей. Если у вас нет доступа к этим файлам, вам нужно будет получить их от разработчиков shiftlab_ocr или обучить модели самостоятельно.
Также убедитесь, что у вас установлена правильная версия shiftlab_ocr и все её зависимости. Возможно, потребуется установить библиотеку непосредственно из репозитория:
bash
git clone https://github.com/path/to/shiftlab_ocr.git
cd shiftlab_ocr
pip3 install -e .
Проблема в правах доступа и некорректном форматировании скрипта. Вот исправленная версия:
bash
#!/bin/bash
# Directory for weights and temporary files
WEIGHTS_DIR="$HOME/.shiftlab_ocr/weights"
TEMP_DIR=$(mktemp -d)
mkdir -p "$WEIGHTS_DIR"
# Cleanup on exit
trap 'rm -rf "$TEMP_DIR"' EXIT
# Check dependencies
check_dependencies() {
command -v pdfimages >/dev/null 2>&1 || { echo "Please install poppler-utils (pdfimages)"; exit 1; }
command -v ddjvu >/dev/null 2>&1 || { echo "Please install djvulibre-bin"; exit 1; }
command -v python3 >/dev/null 2>&1 || { echo "Please install python3"; exit 1; }
python3 -c "import torch" 2>/dev/null || { echo "Please install torch: pip3 install torch"; exit 1; }
python3 -c "import torchvision" 2>/dev/null || { echo "Please install torchvision: pip3 install torchvision"; exit 1; }
python3 -c "import PIL" 2>/dev/null || { echo "Please install Pillow: pip3 install Pillow"; exit 1; }
python3 -c "import tqdm" 2>/dev/null || { echo "Please install tqdm: pip3 install tqdm"; exit 1; }
}
# Check if weights exist
check_weights() {
if [ ! -f "$WEIGHTS_DIR/weights.pt" ] || [ ! -f "$WEIGHTS_DIR/ocr_transformer_4h2l_simple_conv_64x256.pt" ]; then
echo "Model weights not found in $WEIGHTS_DIR"
echo "Required files:"
echo "- weights.pt"
echo "- ocr_transformer_4h2l_simple_conv_64x256.pt"
exit 1
fi
}
# Help message
show_help() {
echo "Usage: $0 [-i INPUT_FILE] [-o OUTPUT_FILE]"
echo "Convert PDF/DJVU/PNG/JPG documents to text"
echo ""
echo "Options:"
echo " -i Input file (PDF, DJVU, PNG or JPG)"
echo " -o Output text file (default: output.txt)"
exit 1
}
# Create Python script
create_python_script() {
cat > "$TEMP_DIR/ocr.py" << 'EOF'
import sys
import os
from shiftlab_ocr.doc2text.reader import Reader
from tqdm import tqdm
weights_dir = os.path.expanduser("~/.shiftlab_ocr/weights")
reader = Reader(
yolo_path=os.path.join(os.path.dirname(__file__), "yolov5"),
detector_weights=os.path.join(weights_dir, "weights.pt"),
recognizer_weights=os.path.join(weights_dir, "ocr_transformer_4h2l_simple_conv_64x256.pt")
)
def process_image(input_file, output_file):
try:
text, _ = reader.doc2text(input_file)
with open(output_file, 'a', encoding='utf-8') as f:
f.write(text + '\n')
return True
except Exception as e:
print(f"Error processing {input_file}: {str(e)}")
return False
if __name__ == "__main__":
input_file = sys.argv[1]
output_file = sys.argv[2]
if not os.path.exists(input_file):
print(f"Input file {input_file} does not exist")
sys.exit(1)
success = process_image(input_file, output_file)
if not success:
sys.exit(1)
EOF
chmod +x "$TEMP_DIR/ocr.py"
}
# Process images function
process_images() {
local total=$(ls "$TEMP_DIR"/*.{png,jpg} 2>/dev/null | wc -l)
local counter=0
for img in "$TEMP_DIR"/*.{png,jpg}; do
[ -e "$img" ] || continue
counter=$((counter + 1))
echo -ne "Processing image $counter/$total\r"
python3 "$TEMP_DIR/ocr.py" "$img" "$output"
done
echo -e "\nDone processing images"
}
# Parse arguments
while getopts "i:o:h" opt; do
case $opt in
i) input="$OPTARG";;
o) output="${OPTARG:-output.txt}";;
h) show_help;;
\?) show_help;;
esac
done
if [ -z "$input" ]; then
show_help
fi
# Run checks
check_dependencies
check_weights
# Create Python script
create_python_script
# Process based on file extension
case "${input,,}" in
*.pdf)
echo "Converting PDF to images..."
pdfimages -png "$input" "$TEMP_DIR/page"
process_images
;;
*.djvu)
echo "Converting DJVU to images..."
ddjvu -format=png -mode=black -page=1- "$input" "$TEMP_DIR/page_%d.png"
process_images
;;
*.png|*.jpg|*.jpeg)
cp "$input" "$TEMP_DIR/page.png"
process_images
;;
*)
echo "Unsupported file format"
exit 1
;;
esac
echo "Text saved to: $output"
Сохраните этот скрипт как doc2text.sh и сделайте его исполняемым:
bash
chmod +x doc2text.sh
Перед использованием установите необходимые зависимости: