Repository navigation
Folders and files
| Name | Name | Last commit date | ||
|---|---|---|---|---|
Repository files navigation
# Extract Text from OCR JSON Files
## Description
This Python script extracts text content and page numbers from JSON files generated by OCR (Optical Character Recognition) processes, such as Google Vision API. It processes all JSON files in a specified directory, extracts the text and corresponding page numbers, cleans the text by removing newlines and tabs, sorts the pages by page number, and outputs the combined text to a single file.
It is specifically useful when using the Google Vision OCR
## Requirements
- Python 3.x
- Standard library modules: json, os, sys, glob (no external dependencies required)
## Usage
Run the script from the command line:
```
python extract_text.py [directory]
```
- `directory`: Optional path to the directory containing JSON files. If not provided, uses the current directory.
## Input Format
The script expects JSON files with the following structure:
```json
{
"responses": [
{
"context": {
"pageNumber": 1
},
"fullTextAnnotation": {
"text": "Extracted text content here..."
}
}
]
}
```
## Output
- Creates `extracted_text.txt` in the specified directory
- Format: Each page is prefixed with "Page X" followed by the extracted text
- Pages are sorted by page number
- Text is cleaned (newlines and tabs replaced with spaces)
## Error Handling
- Skips files that cannot be parsed or are missing required fields
- Reports errors for invalid directories or file access issues
- Continues processing remaining files if individual files fail
## Example
```
python extract_text.py ./ocr_files
```
This will process all .json files in the `ocr_files` directory and create `extracted_text.txt` with the combined, sorted text content.