-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.php
305 lines (275 loc) · 10.2 KB
/
index.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
<?php
/**
* A simple resource-oriented server that performs OCR on an image file.
* Currently uses tesseract (http://code.google.com/p/tesseract-ocr/)
* as the OCR engine.
*
* Written in the Slim micro-framework, slimframework.com.
*
* Released into the Public Domain/distributed under the unlicense/CC0.
*/
require 'config.php';
// Slim setup.
require 'vendor/autoload.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->config('log.enabled', $log_enabled);
ini_set('max_execution_time', $max_exection_time);
/**
* Slim middleware hook that fires before every request to perform
* client authorization by token or IP address.
*
* @param object $app
* The global $app object instantiated at the top of this file.
*/
$app->hook('slim.before', function () use ($app) {
global $tokens;
global $allowed_ip_addresses;
$request = $app->request();
// Checks to see if client API token is in registered list. If
// $tokens is not empty, all clients must send an X-Auth-Key
// request header containing a valid key.
if (count($tokens)) {
if (!in_array($request->headers('X-Auth-Key'), $tokens)) {
$app->halt(403);
}
}
// Check if client is in IP whitelist. If $allowed_ip_addresses
// is not empty, all client IP addresses must match a regex
// defined in that array.
if (count($allowed_ip_addresses)) {
foreach ($allowed_ip_addresses as $range) {
if (!preg_match($range, $request->getIp())) {
$app->halt(403);
}
}
}
});
/**
* Route for PUT /page. The request body will contain the image file.
* Example request: curl -X PUT --data-binary @/path/to/image/file.jpg http://host/ocr_rest/page/file.jpg
*
* @param string $filename
* The filename appended to /page, tokenized by :filename.
* @param object $app
* The global $app object instantiated at the top of this file.
*/
$app->put('/page/:filename', function ($filename) use ($app) {
global $paths;
global $allowed_image_extensions;
// Set up logging (writes to STDERR).
$log = $app->getLog();
// Check to make sure that the file's extension is in the list of
// allowed values.
$file_path_info = pathinfo($filename);
if (!in_array($file_path_info['extension'], $allowed_image_extensions)) {
$log->debug("Image file format not allowed: " . $filename);
$app->halt(400);
}
// Create the subdirectory where the images and transcripts will be written,
// if it does not already exist.
if (!file_exists($paths['image_base_dir'])) {
mkdir($paths['image_base_dir'], 0777, TRUE);
}
if (!file_exists($paths['transcript_base_dir'])) {
mkdir($paths['transcript_base_dir'], 0777, TRUE);
}
$request = $app->request();
// Get the image content from the request body.
$page_image_content = $request->getBody();
// Write out the image file.
$image_input_path = $paths['image_base_dir'] . $filename;
if (file_put_contents($image_input_path, $page_image_content)) {
$log->debug("Image output path from PUT succeeded: " . $image_input_path);
$app->halt(201);
}
else {
$log->debug("Image output path from PUT failed: " . $image_input_path);
$app->halt(500);
}
});
/**
* Route for GET /page. Example requests: curl -X GET -v -H 'Accept: text/html' http://host/ocr_rest/page/file.jpg
* and curl -X GET -v -H 'Accept: text/plain`' http://host/ocr_rest/page/file.jpg
*
* @param string $filename
* The filename appended to /page, tokenized by :filename.
* @param object $app
* The global $app object instantiated at the top of this file.
*/
$app->get('/page/:filename', function ($filename) use ($app) {
global $paths;
$request = $app->request();
$image_input_path = $paths['image_base_dir'] . $filename;
// Set up logging (writes to STDERR).
$log = $app->getLog();
// Check to see if the image file exists and if not, return a 204 No Content
// response.
if (!file_exists($image_input_path)) {
$log->debug("Image not found in GET: " . $image_input_path);
$app->halt(204);
}
// If the client wants HTML, generate hocr output.
if (preg_match('/text\/html/', $request->headers('Accept'))) {
$transcript_output_path = getTranscriptPathFromImagePath($image_input_path);
$log->debug("Transcript output path: " . $transcript_output_path);
// Execute the OCR command.
$command = $paths['ocr_engine'] . ' ' . escapeshellarg($image_input_path) . ' ' .
$transcript_output_path . ' hocr';
$log->debug("Command: " . $command);
$time_pre = microtime(true);
$ret = exec($command, $ret, $exit_value);
$time_post = microtime(true);
$exec_time = $time_post - $time_pre;
if ($exit_value) {
$log->debug("Exit value for $command was not 0: " . $ret);
}
else {
$log->debug("Transcript creation time (seconds): " . $exec_time);
}
// Write out transcript to the client. Tesseract adds the extension
// .html to its HOCR output file.
$transcript = file_get_contents($transcript_output_path . '.html');
$app->response->headers->set('Content-Type', 'text/html;charset=utf-8');
$app->response->setBody($transcript);
}
// If the client wants text, generate text output.
elseif (preg_match('/text\/plain/', $request->headers('Accept'))) {
$transcript_output_path = getTranscriptPathFromImagePath($image_input_path);
$log->debug("Transcript output path: " . $transcript_output_path);
// Execute the OCR command.
$command = $paths['ocr_engine'] . ' ' . escapeshellarg($image_input_path) . ' ' .
$transcript_output_path;
$log->debug("Command: " . $command);
$time_pre = microtime(true);
$ret = exec($command, $ret, $exit_value);
$time_post = microtime(true);
$exec_time = $time_post - $time_pre;
if ($exit_value) {
$log->debug("Exit value for $command was not 0: " . $ret);
}
else {
$log->debug("Transcript creation time (seconds): " . $exec_time);
}
// Write out transcript to the client. Tesseract adds the extension
// .txt to its plain text output file.
$transcript = file_get_contents($transcript_output_path . '.txt');
$app->response->headers->set('Content-Type', 'text/plain;charset=utf-8');
$app->response->setBody($transcript);
}
else {
$log->debug("No Accept request header provided, don't know what to do.");
$app->halt(300);
}
});
/**
* Route for DELETE /page. Returns no request body, only returns a reponse code
* of either 200 (on success) or 500 (on failure).
* Example request: curl -X DELETE http://host/ocr_rest/page/file.jpg
*
* @param string $filename
* The filename appended to /page, tokenized by :filename.
* @param object $app
* The global $app object instantiated at the top of this file.
*/
$app->delete('/page/:filename', function ($filename) use ($app) {
global $paths;
$image_input_path = $paths['image_base_dir'] . $filename;
// Set up logging (writes to STDERR).
$log = $app->getLog();
// Check to see if the image file exists and if not, return a 204 No Content
// response.
if (!file_exists($image_input_path)) {
$log->debug("Image not found in GET: " . $image_input_path);
$app->halt(204);
}
// Delete the image file.
if (unlink($image_input_path)) {
$log->debug("Image DELETE succeeded: " . $image_input_path);
// Delete the corresponding transcripts. Assumes that the image file existed and
// was successfully deleted.
$txt_transcript_path = getTranscriptPathFromImagePath($image_input_path) . '.txt';
if (file_exists($txt_transcript_path)) {
if (unlink($txt_transcript_path)) {
$log->debug("Text transcript DELETE succeeded: " . $txt_transcript_path);
}
}
$html_transcript_path = getTranscriptPathFromImagePath($image_input_path) . '.html';
if (file_exists($html_transcript_path)) {
$log->debug("HTML transcript DELETE succeeded: " . $html_transcript_path);
unlink($html_transcript_path);
}
$app->halt(200);
}
else {
$app->halt(500);
}
});
/**
* Route for GET /alternates. Example requests: curl -X GET -v http://host/ocr_rest/alternates
*
* @param object $app
* The global $app object instantiated at the top of this file.
*/
$app->get('/alternates', function () use ($app) {
global $alternates;
$request = $app->request();
// Set up logging (writes to STDERR).
$log = $app->getLog();
if (!count($alternates)) {
$log->debug("No alternates found in GET");
$app->halt(204);
}
// Return body content text containing all alternates separated by
// PHP_EOL, so it can be split by the client for randomization.
$body = implode(PHP_EOL, $alternates);
$app->response->headers->set('Content-Type', 'text/plain;charset=utf-8');
$app->response->setBody($body);
});
/**
* Route for GET /alternate. Example requests: curl -X GET -v http://host/ocr_rest/alternate
*
* @param object $app
* The global $app object instantiated at the top of this file.
*/
$app->get('/alternate', function () use ($app) {
global $alternates;
$request = $app->request();
// Set up logging (writes to STDERR).
$log = $app->getLog();
if (!count($alternates)) {
$log->debug("No alternates found in GET");
$app->halt(204);
}
// Return a single, randomly chosen alternate in the response body.
$key = array_rand($alternates);
$app->response->headers->set('Content-Type', 'text/plain;charset=utf-8');
$app->response->setBody($alternates[$key]);
});
// Run the Slim app.
$app->run();
/**
* Functions.
*/
/**
* Creates a path to a transcript from an image path.
*
* @param string $image_path
* The full path to the image being processed. For example:
* /tmp/ocr_images/Hutchinson1794-1-0253.jpg
*
* @return string
* The full path to the transcript file corresponding to the image without an extension.
* For example: /tmp/docr_transcripts/Hutchinson1794-1-0253
*/
function getTranscriptPathFromImagePath($image_path) {
global $paths;
// Replace the image base directory configuration value with the
// transcript base directory configuration value.
$image_base_path_pattern = '#' . $paths['image_base_dir'] . '#';
$tmp_path = preg_replace($image_base_path_pattern, $paths['transcript_base_dir'], $image_path);
$path_parts = pathinfo($tmp_path);
$transcript_path = $path_parts['dirname'] . DIRECTORY_SEPARATOR . $path_parts['filename'];
return $transcript_path;
}
?>