Skip to content

Instantly share code, notes, and snippets.

@sergiks
Last active February 21, 2020 19:38
Show Gist options
  • Save sergiks/7cb1dafc8ca682cd5845542df79b3e83 to your computer and use it in GitHub Desktop.
Save sergiks/7cb1dafc8ca682cd5845542df79b3e83 to your computer and use it in GitHub Desktop.
Lumen controller "talking" to TensorFlow Serving REST API
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class TensorController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
//
}
public function showForm()
{
return view('form');
}
public function checkImage(Request $request) {
if (!$request->hasFile('image')) {
return 'No image uploaded';
}
$imageFile = $request->file('image');
// resize image unproportionally to 380x380
list($width, $height) = getimagesize($imageFile);
$src = imagecreatefromjpeg($imageFile);
$dst = imagecreatetruecolor(380, 380);
imagecopyresampled($dst, $src, 0, 0, 0, 0, 380, 380, $width, $height);
unlink($imageFile);
// convert to JSON array
$json = '{"inputs":[[';
for ($y = 0; $y < 380; $y++) {
$json .= '[';
for ($x = 0; $x < 380; $x++) {
$rgb = imagecolorat($dst, $x, $y);
$r = (($rgb >> 16) & 0xFF) / 0xFF;
$g = (($rgb >> 8) & 0xFF) / 0xFF;
$b = ($rgb & 0xFF) / 0xFF;
$json .= sprintf('[%06f,%06f,%06f]', $r, $g, $b);
if ($x < 380 - 1) $json .= ',';
}
$json .= ']';
if ($y < 380 - 1) $json .= ',';
}
$json .= ']]}';
// return $json;
// query TensorFlow Serving
$ch = curl_init('http://tensorflow:8501/v1/models/orbit:predict');
curl_setopt_array ($ch, [
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_CONNECTTIMEOUT => 2, // TODO: handle timeout error
CURLOPT_TIMEOUT => 20, // TODO: handle timeout error
CURLOPT_POSTFIELDS => $json,
]);
$response = curl_exec($ch);
$result = json_decode($response);
if (!$result) return 'Response JSON decode error: ' . $response;
if (isset($result->error)) return 'Error: ' . $response;
// { "outputs": [ [ 0.114583552, 0.104765795, 0.778343379, 0.00230731 ] ] }
if (isset($result->outputs, $result->outputs[0])) {
$weights = $result->outputs[0];
$maxValue = max($weights);
$maxIndex = array_search($maxValue, $weights);
if ($maxValue < 0.9) $maxIndex = 2; // "not"
$names_dict = ['bank_pack', 'mega_pack', 'not', 'standart_pack'];
return $names_dict[$maxIndex];
} else {
return 'No outputs in the response: ' . $response;
}
return $result;
return 'OK';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment