# OCR

> Send scanned PDFs to Firecrawl for OCR and handle its failures.

A scanned PDF, or one with image-only pages that have no text for anydoc to extract, fails with `ConvertError::NeedsOcr`. Call `.ocr()` before `.markdown()` to send such a PDF to [Firecrawl Parse](https://docs.firecrawl.dev) and get its Markdown back:

```rust
use laravel::prelude::*;
use laravel_anydoc::Anydoc;

pub async fn scan(anydoc: Inject<Anydoc>) -> laravel::Result<String> {
    anydoc.disk("s3")?.file("scans/scan.pdf").ocr().markdown().await
}
```

The document still converts locally first, so `.ocr()` costs nothing for documents that do not need it. Only a PDF that fails with `NeedsOcr` goes to Firecrawl, whole, pages with text included. Without `.ocr()`, it fails with `Error::Convert` and nothing is sent.

OCR produces Markdown only, so `.ocr()` returns a builder without `.document()`. Call `.format()` before `.ocr()`.

## Firecrawl requests

The request goes to `{ANYDOC_FIRECRAWL_API_URL}/v2/parse`, with `ANYDOC_FIRECRAWL_API_KEY` as a bearer token when it is set and `ANYDOC_FIRECRAWL_TIMEOUT` as its timeout. Firecrawl also accepts requests without a key, at lower limits. See [Configuration](https://hosmelq.com/docs/laravel-anydoc-rust/v0.1/configuration/). The PDF is sent under the file's name, or `document.pdf` for bytes.

## Errors

When Firecrawl fails, the conversion fails with `laravel_anydoc::Error::Ocr`, which responds with `502 Bad Gateway`. It wraps an `OcrError` that says why: the connection failed, Firecrawl rejected the API key, the account is out of credits, the request was rate-limited, Firecrawl responded with another status or rejected the document, or the response had no Markdown.

Downcast the error to handle one of these cases:

```rust
use laravel::prelude::*;
use laravel_anydoc::{Anydoc, Error, OcrError};

pub async fn scan(anydoc: Inject<Anydoc>) -> laravel::Result<String> {
    let error = match anydoc.file("storage/app/scan.pdf").ocr().markdown().await {
        Ok(markdown) => return Ok(markdown),
        Err(error) => error,
    };

    match error.downcast_ref::<Error>() {
        Some(Error::Ocr(OcrError::OutOfCredits(_))) => Ok(String::from("OCR is unavailable right now.")),
        _ => Err(error),
    }
}
```

## Testing

The request goes through `laravel::http::client`, so tests fake Firecrawl with `client::fake()`; see [Real conversions](https://hosmelq.com/docs/laravel-anydoc-rust/v0.1/basic-usage/testing/#real-conversions).
