{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import inception_resnet_v1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2\n",
    "from skimage.transform import resize\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img=cv2.imread('nas/Face/test/test2.jpg')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "face_cascade = cv2.CascadeClassifier(\"Face-Clock/model/cv2/haarcascade_frontalface_alt2.xml\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "faces = face_cascade.detectMultiScale(img,scaleFactor=1.1,minNeighbors=3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 人臉偵測處理回傳結果矩陣\n",
    "image_size=160\n",
    "def face_cropped(img,faces, margin):    \n",
    "    aligned_images = []\n",
    "    for f in faces:\n",
    "        (x, y, w, h) = f\n",
    "        cropped = img[y-margin//2:y+h+margin//2,x-margin//2:x+w+margin//2, :]\n",
    "        aligned = resize(cropped, (image_size, image_size), mode='reflect')\n",
    "        aligned_images.append(aligned)\n",
    "            \n",
    "    return np.array(aligned_images)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "inception_resnet_v1.calc_embs(face_cropped(img,faces,10))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from facenet_predict import InceptionResNetV1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model=InceptionResNetV1()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model.predict()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "from skimage.transform import resize\n",
    "# 人臉偵測處理回傳結果矩陣\n",
    "def load_and_align_images(filepaths, margin):\n",
    "    image_size=160\n",
    "    cascade_path = 'Face-Clock/model/cv2/haarcascade_frontalface_alt2.xml'\n",
    "    cascade = cv2.CascadeClassifier(cascade_path)\n",
    "    \n",
    "    aligned_images = []\n",
    "    for filepath in filepaths:\n",
    "        img = cv2.imread(filepath)\n",
    "\n",
    "        faces = cascade.detectMultiScale(img,\n",
    "                                         scaleFactor=1.1,\n",
    "                                         minNeighbors=3)\n",
    "        if(len(faces)==0):\n",
    "            print('notthing')\n",
    "            continue\n",
    "        (x, y, w, h) = faces[0]\n",
    "        cropped = img[y-margin//2:y+h+margin//2,\n",
    "                      x-margin//2:x+w+margin//2, :]\n",
    "        aligned = resize(cropped, (image_size, image_size), mode='reflect')\n",
    "        aligned_images.append(aligned)\n",
    "            \n",
    "    return np.array(aligned_images)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 影像預處理\n",
    "def prewhiten(x):\n",
    "    if x.ndim == 4:\n",
    "        axis = (1, 2, 3)\n",
    "        size = x[0].size\n",
    "    elif x.ndim == 3:\n",
    "        axis = (0, 1, 2)\n",
    "        size = x.size\n",
    "    else:\n",
    "        print(x.ndim)\n",
    "        raise ValueError('Dimension should be 3 or 4')\n",
    "\n",
    "    mean = np.mean(x, axis=axis, keepdims=True)\n",
    "    std = np.std(x, axis=axis, keepdims=True)\n",
    "    std_adj = np.maximum(std, 1.0/np.sqrt(size))\n",
    "    y = (x - mean) / std_adj\n",
    "    return y\n",
    "\n",
    "def l2_normalize(x, axis=-1, epsilon=1e-10):\n",
    "    output = x / np.sqrt(np.maximum(np.sum(np.square(x), axis=axis, keepdims=True), epsilon))\n",
    "    return output"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "prewhiten(load_and_align_images(['nas/Face/train/Bruce/Bruce02.jpg'],10))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import time\n",
    "from datetime import datetime,timezone,timedelta"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "t=time.time()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dt=datetime.utcfromtimestamp(t)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tzutc_8 = timezone(timedelta(hours=8))\n",
    "local_dt = dt.astimezone(tzutc_8)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dt = local_dt.strftime('%Y_%m_%d_%H_%M_%S_%f')+'.jpg'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a='1561612926.4031167'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pymysql"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [],
   "source": [
    "db=pymysql.connect('192.168.0.5','root','xMd2k5aK','rd')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [],
   "source": [
    "cursor = db.cursor()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [],
   "source": [
    "# sql=\"SELECT id FROM employee WHERE id LIKE 'RD{0}%'\".format('105')\n",
    "\n",
    "# sql=\"SELECT name FROM `employee` WHERE id='RD10501'\"\n",
    "\n",
    "sql=\"SELECT id FROM employee WHERE id LIKE 'RD{0}%'\".format(100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [],
   "source": [
    "a=cursor.execute(sql)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "()"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "cursor.fetchall()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "int"
      ]
     },
     "execution_count": 60,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sql=\"\"\"INSERT INTO `employee` (`id`, `name`, `english_name`, `phone`) VALUES ('{0}', '{1}', '{2}', '{3}')\"\"\".format('RD10506','test','test','09875464')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cursor.execute(sql)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "db.commit()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from influxdb import InfluxDBClient\n",
    "import requests\n",
    "import datetime"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "frame=cv2.imread('./nas/Face/train/Allen/Allen03.jpg')\n",
    "imencoded = cv2.imencode(\".jpg\", frame)[1]\n",
    "file = {'file': ('image.jpg', imencoded.tostring(), 'image/jpeg', {'Expires': '0'})}\n",
    "response=requests.post(os.path.join('http://192.168.5.205:8000','whois'),files=file)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "t=response.json()['time']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "client=InfluxDBClient(host='192.168.0.6',port=8086,username='root',password='xMd2k5aK',database='rd')\n",
    "json_body = [\n",
    "    {\n",
    "        \"measurement\": 'login_',\n",
    "        \"time\": datetime.datetime.utcfromtimestamp(float(t)),\n",
    "        \"fields\": {\n",
    "            \"name\": 'test',\n",
    "            'snapshot':'test.jpg'\n",
    "        }\n",
    "    }\n",
    "]\n",
    "client.write_points(json_body)\n",
    "client.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = \"2019-07-01 00:26:22\"\n",
    "import time\n",
    "timeArray = time.strptime(a, \"%Y-%m-%d %H:%M:%S\")\n",
    "timeStamp = time.mktime(timeArray)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1561940782.0"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "timeStamp"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1562126418.3251102"
      ]
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "time.time()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
