BiFace_Server_Lite/controllers/ApiController.php
2021-01-19 14:27:28 +07:00

431 lines
17 KiB
PHP

<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\helpers\FileHelper;
use app\models\CaptureLogs;
use app\models\ListManagement;
use app\models\common;
/**
* CardController implements the CRUD actions for Card model.
*/
class ApiController extends Controller {
/**
* {@inheritdoc}
*/
public function behaviors() {
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
public function actionSaveLogs() {
if (Yii::$app->request->post()) {
$post = Yii::$app->request->bodyParams;
$model = new \app\models\FaceLogs();
$model->create($post);
Yii::$app->response->format = "json";
return ["stt" => true];
}
}
public function actionSyncUrl() {
if (Yii::$app->request->post()) {
$post = Yii::$app->request->bodyParams;
$sync = \app\models\SyncUrl::find()->one();
if ($sync) {
$sync->data = $post['url'];
$sync->save();
} else {
$model = new \app\models\SyncUrl();
$model->create($post);
}
Yii::$app->response->format = "json";
return ["stt" => true];
}
}
public function actionGetLogs() {
if (Yii::$app->request->post()) {
$post = Yii::$app->request->bodyParams;
$time = date_format(date_create_from_format('Y-m-d H:i:s', $post['time']), 'U');
$key = common::generateRandomString();
$RootFolder = Yii::getAlias('@webroot') . "/data/uploads";
$targetPath = $RootFolder . "/face";
$fileName = "face_" . $key . "_" . $time . ".png";
FileHelper::createDirectory($targetPath, 0777);
file_put_contents($targetPath . "/" . $fileName, base64_decode($post['image']));
$totalsLogs = CaptureLogs::find()->count();
if ($totalsLogs >= \Yii::$app->params['maxLogs']) {
$lastLogs = CaptureLogs::find()->orderBy(["id" => SORT_ASC])->limit(1)->one();
unlink("/var/www/html/BiFace_Server_Lite/web/data/uploads/face/" . $lastLogs->image);
$lastLogs->delete();
}
$model = new CaptureLogs();
$logs = $model->create([
"Staff" => $post["id"],
"Time" => $time,
"Image" => $fileName,
"Confidence" => strval($post["confidence"])
]);
$server_ip = \app\models\SyncUrl::findOne(['key_config' => 'server_api']);
$ip = "https://dev-dc.beetai.com";
if ($server_ip)
$ip = $server_ip->data;
if ($this->is_connected($ip) && $logs) {
$device_id = \app\models\SyncUrl::findOne(['key_config' => 'device_id']);
$id_camera = 209;
if ($device_id)
$id_camera = intval($device_id->data);
$logsInfo = CaptureLogs::findOne($logs);
$staffInfo = ListManagement::findOne($post['id']);
$tk = "";
$token = \app\models\SyncUrl::findOne(['key_config' => 'token']);
if ($token)
$tk = $token->data;
$res = json_decode(file_get_contents($ip . "/api/oem/face_recognition?token=" . $tk, false, stream_context_create([
'http' => [
'header' => "Content-Type: application/json",
'method' => "POST",
'content' => json_encode([
'image' => base64_encode(file_get_contents("/var/www/html/BiFace_Server_Lite/web/data/uploads/face/" . $fileName)),
'camera_id' => strval($id_camera),
'frametime' => date("Y-m-d H:i:s", $time),
'idCard' => $staffInfo ? strval($staffInfo->code) : "0",
"person_id" => "123",
"timezone" => "+7"
])
]
])), true);
if ($res['status'] == 10000) {
$logsInfo->sync_status = 1;
$logsInfo->save();
}
}
Yii::$app->response->format = "json";
return ["status" => "success"];
}
}
public function actionGetAllFeatures($offset = 0, $limit = 10) {
$listManagement = ListManagement::find()->limit($limit)->offset($offset)->all();
$allFeatures = [];
foreach ($listManagement as $key => $value) {
$features = json_decode($value->image, true);
$f = [];
foreach ($features as $k => $v) {
$f[] = $v['features'];
if (isset($v['features512']))
if (count($v['features512']))
$f[] = $v['features512'];
}
$allFeatures[] = [
"id" => $value->id,
"name" => $this->convert_vi_to_en($value->name),
"features" => $f
];
}
Yii::$app->response->format = "json";
return $allFeatures;
}
public function actionData() {
if (Yii::$app->request->post()) {
Yii::$app->response->format = "json";
return ListManagement::find()->orderBy(['last_modified' => SORT_DESC])->all();
}
}
public function actionFullData() {
if (Yii::$app->request->post()) {
Yii::$app->response->format = "json";
$lists = ListManagement::find()->andWhere(["IN", "code", Yii::$app->request->post()])->orderBy(['last_modified' => SORT_DESC])->all();
$res = [];
foreach ($lists as $key => $value) {
$f = [];
$features = json_decode($value->image, true);
foreach ($features as $k => $v) {
$f[] = ["url" => base64_encode(file_get_contents(Yii::getAlias('@webroot') . "/data/uploads/face/" . $v['url'])), "features" => $v['features']];
}
$res[] = [
"id" => $value->id,
"code" => $value->code,
"type" => $value->type,
"name" => $value->name,
"gender" => $value->gender,
"birthday" => $value->birthday,
"telephone" => $value->telephone,
"department" => $value->address,
"time" => $value->time,
"images" => $f
];
}
return $res;
}
}
public function actionGetAllImage() {
Yii::$app->response->format = "json";
$lists = ListManagement::find()->orderBy(['id' => SORT_DESC])->all();
$res = [];
foreach ($lists as $key => $value) {
$f = [];
$features = json_decode($value->image, true);
foreach ($features as $k => $v) {
$f[] = Yii::$app->request->hostInfo . "/data/uploads/face/" . $v['url'];
}
$res[] = [
"id" => $value->id,
"code" => $value->code,
"type" => $value->type,
"name" => $value->name,
"gender" => $value->gender,
"birthday" => $value->birthday,
"telephone" => $value->telephone,
"address" => $value->address,
"time" => $value->time,
"image" => $f
];
}
return $res;
}
public function actionResetData() {
// return file_get_contents("https://bischool.beetai.com/view/image/5f7c1b22dfe5aaf427a6dfa1");
\Yii::$app->db->createCommand()->truncateTable('capture_logs')->execute();
\Yii::$app->db->createCommand()->truncateTable('list_management')->execute();
}
public function convert_vi_to_en($str) {
$str = preg_replace("/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/", "a", $str);
$str = preg_replace("/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/", "e", $str);
$str = preg_replace("/(ì|í|ị|ỉ|ĩ)/", "i", $str);
$str = preg_replace("/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/", "o", $str);
$str = preg_replace("/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/", "u", $str);
$str = preg_replace("/(ỳ|ý|ỵ|ỷ|ỹ)/", "y", $str);
$str = preg_replace("/(đ)/", "d", $str);
$str = preg_replace("/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/", "A", $str);
$str = preg_replace("/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/", "E", $str);
$str = preg_replace("/(Ì|Í|Ị|Ỉ|Ĩ)/", "I", $str);
$str = preg_replace("/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/", "O", $str);
$str = preg_replace("/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/", "U", $str);
$str = preg_replace("/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/", "Y", $str);
$str = preg_replace("/(Đ)/", "D", $str);
//$str = str_replace(" ", "-", str_replace("&*#39;","",$str));
return $str;
}
public function getCurrentTime() {
$time = microtime();
$time = explode(' ', $time);
return $time[1] + $time[0];
}
public function actionAutoGenFeature() {
Yii::$app->response->format = "json";
$updating = \app\models\SyncUrl::findOne(['key_config' => 'updating']);
if (!$updating) {
$model = new \app\models\SyncUrl();
$model->create([
'key_config' => "updating",
'data' => "false"
]);
$updating = \app\models\SyncUrl::findOne(['key_config' => 'updating']);
}
if ($updating->data === "true") {
$txt = "\n" . date("H:i:s d/m/Y") . " " . "updating";
file_put_contents(date('Ymd') . "_logs.txt", $txt, FILE_APPEND);
return ["status" => false];
}
$currentCache = json_decode(file_get_contents("http://localhost:2305/current-cache"), true);
if ($currentCache['n_128'] == $currentCache['n_512']) {
$txt = "\n" . date("H:i:s d/m/Y") . " " . "success";
file_put_contents(date('Ymd') . "_logs.txt", $txt, FILE_APPEND);
return ["status" => false];
}
$updating->data = "true";
$updating->save();
$processTime = [];
set_time_limit(0);
$lists = ListManagement::find()->all();
foreach ($lists as $key => $value) {
$extract = false;
$images = json_decode($value->image, true);
$newImgs = [];
$temp = [];
foreach ($images as $k => $v) {
if (!isset($v['features512']) || (isset($v['features512']) && count($v['features512']) == 0)) {
$start = $this->getCurrentTime();
$features = json_decode(common::requestToEngine("/get-feature", [
"image_paths" => [
["url" => "/var/www/html/BiFace_Server_Lite/web/data/uploads/face/" . $v['url'], "type" => "raw"]
],
"type" => "512"
]), true);
$finish = $this->getCurrentTime();
$temp[] = round(($finish - $start), 4);
$v['features512'] = $features['results'][0]['feature512'];
$extract = true;
}
$newImgs[] = $v;
}
if ($extract) {
$processTime['extract'] = $temp;
$start = $this->getCurrentTime();
$value->image = json_encode($newImgs);
$value->save();
$finish = $this->getCurrentTime();
$processTime["updateDB"] = round(($finish - $start), 4);
$txt = "\n" . json_encode($processTime);
file_put_contents(date('Ymd') . ".txt", $txt, FILE_APPEND);
}
}
file_get_contents("http://localhost:2305/update-feature");
$updating->data = "false";
$updating->save();
return ["status" => true];
}
public function actionSync() {
Yii::$app->response->format = "json";
if ($this->is_connected()) {
$server_ip = \app\models\SyncUrl::findOne(['key_config' => 'server_api']);
$ip = "https://dev-dc.beetai.com";
if ($server_ip)
$ip = $server_ip->data;
$device_id = \app\models\SyncUrl::findOne(['key_config' => 'device_id']);
$id_camera = 209;
if ($device_id)
$id_camera = intval($device_id->data);
$ls = CaptureLogs::find()->andWhere(['sync_status' => null])->all();
$tk = "";
$token = \app\models\SyncUrl::findOne(['key_config' => 'token']);
if ($token)
$tk = $token->data;
foreach ($ls as $key => $value) {
$staffInfo = ListManagement::findOne($value->staff_id);
$res = json_decode(file_get_contents($ip . "/api/oem/face_recognition?token=" . $tk, false, stream_context_create([
'http' => [
'header' => "Content-Type: application/json",
'method' => "POST",
'content' => json_encode([
'image' => base64_encode(file_get_contents("/var/www/html/BiFace_Server_Lite/web/data/uploads/face/" . $value->image)),
'camera_id' => strval($id_camera),
'frametime' => date("Y-m-d H:i:s", $value->time),
'idCard' => $staffInfo ? strval($staffInfo->code) : "0",
"person_id" => "123",
"timezone" => "+7"
])
]
])), true);
if ($res['status'] == 10000) {
$value->sync_status = 1;
$value->save();
}
}
}
return ["status" => true];
}
function is_connected($ip = "google.com") {
$connected = @fsockopen($ip, 80);
//website, port (try 80 or 443)
if ($connected) {
$is_conn = true; //action when connected
fclose($connected);
} else {
$is_conn = false; //action in connection failure
}
return $is_conn;
}
public function actionGetNumberPerson() {
return ListManagement::find()->count();
}
public function actionGetTotalFeature() {
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = "json";
$start = $this->getCurrentTime();
$statistics = ListManagement::statisticFeatures();
$finish = $this->getCurrentTime();
$processTime = round(($finish - $start), 4);
return [
"statistics" => $statistics,
"processTime" => $processTime
];
}
}
public function actionCurrentCache() {
return file_get_contents("http://localhost:2305/current-cache");
}
public function actionSaveToken() {
if (Yii::$app->request->post()) {
$post = Yii::$app->request->bodyParams;
$token = \app\models\SyncUrl::findOne(['key_config' => 'token']);
if ($token) {
$token->data = $post['token'];
$token->save();
} else {
$model = new \app\models\SyncUrl();
$model->create([
'key_config' => "token",
'data' => $post['token']
]);
}
Yii::$app->response->format = "json";
return ["status" => true];
}
}
public function actionTest() {
$check = \app\models\SyncUrl::findOne(['key_config' => 'updating']);
$check->data = "false";
$check->save();
return var_dump($check);
// file_get_contents("http://localhost:2305/update-feature");
// return;
set_time_limit(0);
$lists = ListManagement::find()->all();
foreach ($lists as $key => $value) {
$extract = false;
$images = json_decode($value->image, true);
$newImgs = [];
foreach ($images as $k => $v) {
$v['features512'] = [];
$newImgs[] = $v;
}
$value->image = json_encode($newImgs);
$value->save();
}
}
public function actionReGenFeature() {
if (Yii::$app->request->isAjax) {
$updating = \app\models\SyncUrl::findOne(['key_config' => 'updating']);
$updating->data = "false";
return $updating->save();
}
}
}