> ## Documentation Index
> Fetch the complete documentation index at: https://docs.frankieone.com/llms.txt
> Use this file to discover all available pages before exploring further.

# OCR Module

> The Optical Character Recognition (OCR) Module enables document scanning and text extraction in your application. It supports both headed (UI-based) and headless implementations.

## Getting Started

```javascript title="Initialize OCR Module" theme={null}
// Create an OCR module instance
const ocr = oneSdk.component('ocr');
```

## Country-specific screens

To ensure compliance with specific country requirements, document screens are customised for certain countries.

Below is a table summarising the information required for each country:

### Country-Specific screens

| Country         | Required Fields           | Description                                                                 |
| --------------- | ------------------------- | --------------------------------------------------------------------------- |
| Australia       | DL - Document/Card Number | Driver’s license document/card number must be displayed.                    |
| Australia       | Medicare Card Details     | Medicare card color, position on the card, and date of expiry are included. |
| New Zealand     | DL Version Number         | Driver’s license version number is required for display.                    |
| New Zealand     | Passport Expiry Date      | Passport’s date of expiry must be shown.                                    |
| India           | Passport File Number      | The passport file number is a necessary field to be displayed.              |
| Other Countries | Document ID Only          | A generic document screen displaying only the ID/document number is used.   |

## OCR Prefill information

<CardGroup cols={2}>
  <Card title="Address Extraction">
    Extracts addresses from documents for better organization.
  </Card>

  <Card title="Field Validation">
    Ensures extracted information is valid before submission.
  </Card>

  <Card title="Manual Input Options">
    Allows users to manually input details if the OCR extraction is inaccurate or incomplete.
  </Card>
</CardGroup>

## Display Manual Fields:

<Steps>
  <Step title="Open the OCR Review Screen">
    The OCR Review Screen will display the extracted address and manual fields for correction.

    <Callout icon="thumbtack" color="#1A6CFF" iconType="regular">
      The manual address fields always appear on the OCR Review screen regardless of whether the extracted address matches a Google Place.

      If a match is found, the address is automatically divided into the appropriate fields.
      If no match is found, the full address appears in the street name field.

      Users must review the address and correct any validation errors as needed.
    </Callout>
  </Step>

  <Step title="Correct the Address">
    If an invalid or incomplete address is detected, the screen will prompt users to correct it manually.
  </Step>

  <Step title="Validate and Submit">
    Once corrected, the information is validated and submitted.
  </Step>
</Steps>

## Implementation Options

<Tabs>
  <Tab title="Headed Implementation">
    Perfect for applications that need a pre-built UI component.

    <Steps>
      <Step title="Add HTML Container">
        ```html title="index.html" theme={null}
        <div id="ocr"></div>
        ```
      </Step>

      <Step title="Mount OCR Component">
        ```javascript theme={null}
        // Mount OCR to your container element
        ocr.mount('#ocr');
        ```
      </Step>

      <Step title="Configure Viewport (Required)">
        ```html title="index.html" theme={null}
        <head>
          <meta name="viewport" 
                content="width=device-width, initial-scale=1.0" 
                charset="UTF-8" />
          <title>OneSDK OCR</title>
        </head>
        ```
      </Step>
    </Steps>
  </Tab>

  <Tab title="Headless Implementation">
    For custom UI implementations with full control over the document capture experience.

    ```javascript theme={null}
    ocr.on('input_required', (inputInfo, status, callback) => {
      // Your custom image capture logic here
      const capturedImage = await captureDocument(inputInfo);
      callback(capturedImage);
    });
    ```
  </Tab>
</Tabs>

<Callout icon="star" color="#3DD892" iconType="regular">
  You may need to adjust your Content Security Policy (CSP) settings to allow the IDV module to function correctly. Refer to <a href="/docs/v1/onesdk/oneSDK/implementation-guide#content-security-policy-csp-settings">this page</a> for more details.
</Callout>

## OCR Events

<AccordionGroup>
  <Accordion title="ready">
    `ready` os emitted when the OCR is successfully mounted.

    To listen to this event, use:

    ```typescript theme={null}
    ocr.on('ready', () => {
      console.log('idv component is ready')
    }); 
    ```
  </Accordion>

  <Accordion title="detection_complete">
    The OCR component emits a `detection_complete` event when it successfully detects a customer's information. The component emits this event immediately before `results`. To listen to this event, use:

    ```typescript theme={null}
      ocr.on('detection_complete', () => {
        // programatically unmount your component
        setMounted(false);
      })
    ```
  </Accordion>

  <Accordion title="results">
    The component is submitting the end-user data during this event. To listen to this event, use:

    ```typescript theme={null}
    ocr.on('success', 
      (checkStatus, document, entityId) => {
        // you can extract information emitted from success event
        // and use it to your own use
      }
    )
    ```

    where the data types for the parameters are:

    ```json theme={null}
      checkStatus: 'COMPLETE' | 'FAILED',
      document: Object
      entityId: string
    ```

    `checkStatus` will consist of either COMPLETE or FAILED, where

    <>
      <ul>
        <li>“COMPLETE”: The process and the check results are ready.</li>
        <li>"FAILED": The process completed but failed to validate the captured ID and face.</li>
      </ul>
    </>

    `document`: the document object generated after the OCR extract

    `entityId`: FrankieOne’s internal reference for the individual
  </Accordion>

  <Accordion title="detection_failed">
    The component has run unsuccessfully. You can use custom loading spinners or additional styles to handle this event gracefully. To listen to this event, use:

    ```typescript theme={null}
    ocr.on('detection_failed', () => {
    // programatically unmount your component
    setMounted(false);
    })
    ```
  </Accordion>

  <Accordion title="input_required">
    ```typescript theme={null}

    To listen to this event, use:
    ocr.on('input_required', (information, checkStatus) => {
    if (checkStatus === 'WAITING_SELFIE_UPLOAD') {
      console.log("waiting for selfie capture")
    }
    })
    ```

    `input_required` will emit the `entityId` and the current status of the process, such as:

    <>
      <ul>
        <li>Waiting for Document upload `WAITING_DOC_UPLOAD`</li>
        <li>Waiting for selfie upload `WAITING_SELFIE_UPLOAD`</li>
        <li>Uploaded document has invalid type `AWAITING_DOCUMENT_UPLOAD_INVALID_TYPE`</li>
        <li>The process is either incomplete or interrupted `INCOMPLETE` / `INTERRUPTED`.</li>
      </ul>
    </>

    <Callout icon="thumbtack" color="#1A6CFF" iconType="regular">
      For **Incode**, a lack of camera access permissions triggers the `INTERRUPTED` event.
    </Callout>
  </Accordion>

  <Accordion title="error">
    On error, we throw all events from the vendor back to you. To listen to this event, use:

    ```typescript theme={null}
    ocr.on('error', (e) => {
    console.log(e.message, e.payload)
    })
    ```

    <Callout icon="thumbtack" color="#1A6CFF" iconType="regular">
      If you're using **Incode**, the possible messages are: `InternalServerError`, `OSVersionNotSupported`, and `browserNotSupported`
    </Callout>
  </Accordion>
</AccordionGroup>

## Implementation Example

<CodeGroup>
  ```javascript title="Complete Headless Implementation" theme={null}
  const ocr = oneSdk.component('ocr');

  ocr.on('input_required', async (inputInfo, status, callback) => {
    try {
      // Check document type and side required
      console.log(`Need ${inputInfo.side} side of ${inputInfo.documentType}`);
      
      // Your custom image capture implementation
      const imageFile = await captureDocumentImage({
        type: inputInfo.documentType,
        side: inputInfo.side
      });
      
      // Send captured image back to OCR module
      callback(imageFile);
    } catch (error) {
      console.error('Document capture failed:', error);
      // Handle error appropriately
    }
  });
  ```

  ```javascript title="Custom Image Capture Example" theme={null}
  async function captureDocumentImage({ type, side }) {
    // Example using file input
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';
    
    return new Promise((resolve, reject) => {
      input.onchange = (event) => {
        const file = event.target.files[0];
        if (file) {
          resolve(file);
        } else {
          reject(new Error('No file selected'));
        }
      };
      input.click();
    });
  }
  ```
</CodeGroup>

<Callout icon="star" color="#3DD892" iconType="regular">
  ##### Best Practices

  * Validate image quality before submission to reduce OCR failures
  * Implement proper error handling for all status codes
  * Consider device capabilities when choosing implementation type
  * Test with various document types and lighting conditions
</Callout>

<Callout icon="bell" color="#FFCA16" iconType="regular">
  Remember to handle potential errors and provide appropriate feedback to users during the document capture process.
</Callout>
