|
| 1 | +#!/usr/bin/env php |
| 2 | + |
| 3 | +<?php |
| 4 | +// Example of using API4AI OCR text recognition. |
| 5 | + |
| 6 | +// Use 'demo' mode just to try api4ai for free. Free demo is rate limited. |
| 7 | +// For more details visit: |
| 8 | +// https://api4.ai |
| 9 | + |
| 10 | +// Use 'rapidapi' if you want to try api4ai via RapidAPI marketplace. |
| 11 | +// For more details visit: |
| 12 | +// https://rapidapi.com/api4ai-api4ai-default/api/ocr43/details |
| 13 | +$MODE = 'demo'; |
| 14 | + |
| 15 | +// Your RapidAPI key. Fill this variable with the proper value if you want |
| 16 | +// to try api4ai via RapidAPI marketplace. |
| 17 | +$RAPIDAPI_KEY = null; |
| 18 | + |
| 19 | +$OPTIONS = [ |
| 20 | + 'demo' => [ |
| 21 | + 'url' => 'https://demo.api4ai.cloud/ocr/v1/results', |
| 22 | + 'headers' => ['A4A-CLIENT-APP-ID: sample'] |
| 23 | + ], |
| 24 | + 'rapidapi' => [ |
| 25 | + 'url' => 'https://ocr43.p.rapidapi.com/v1/results', |
| 26 | + 'headers' => ["X-RapidAPI-Key: {$RAPIDAPI_KEY}"] |
| 27 | + ] |
| 28 | +]; |
| 29 | + |
| 30 | +// Initialize request session. |
| 31 | +$request = curl_init(); |
| 32 | + |
| 33 | +// Check if path to local image provided. |
| 34 | +$data = ['url' => 'https://storage.googleapis.com/api4ai-static/samples/ocr-1.png']; |
| 35 | +if (array_key_exists(1, $argv)) { |
| 36 | + if (strpos($argv[1], '://')) { |
| 37 | + $data = ['url' => $argv[1]]; |
| 38 | + } else { |
| 39 | + $filename = pathinfo($argv[1])['filename']; |
| 40 | + $data = ['image' => new CURLFile($argv[1], null, $filename)]; |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +// Set request options. |
| 45 | +curl_setopt($request, CURLOPT_URL, $OPTIONS[$MODE]['url']); |
| 46 | +curl_setopt($request, CURLOPT_HTTPHEADER, $OPTIONS[$MODE]['headers']); |
| 47 | +curl_setopt($request, CURLOPT_POST, true); |
| 48 | +curl_setopt($request, CURLOPT_POSTFIELDS, $data); |
| 49 | +curl_setopt($request, CURLOPT_RETURNTRANSFER, true); |
| 50 | + |
| 51 | +// Execute request. |
| 52 | +$result = curl_exec($request); |
| 53 | + |
| 54 | +// Decode response. |
| 55 | +$raw_response = json_decode($result, true); |
| 56 | + |
| 57 | +// Print raw response. |
| 58 | +echo join('', |
| 59 | + ["💬 Raw response:\n", |
| 60 | + json_encode($raw_response), |
| 61 | + "\n"]); |
| 62 | + |
| 63 | +// Parse response and get recognized text. |
| 64 | +$text = $raw_response['results'][0]['entities'][0]['objects'][0]['entities'][0]['text']; |
| 65 | + |
| 66 | +// Close request session. |
| 67 | +curl_close($request); |
| 68 | + |
| 69 | +// Print recognized text. |
| 70 | +echo join('', |
| 71 | + ["\n💬 Recognized text: \n", |
| 72 | + $text, |
| 73 | + "\n"]); |
| 74 | +?> |
0 commit comments