Created
February 22, 2022 15:18
-
-
Save jirawatee/226d634df3f7b63430ddbb9c2d938ef0 to your computer and use it in GitHub Desktop.
Extract data from Thai ID card
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const functions = require("firebase-functions"); | |
exports.myCallable = functions.https.onCall(async (data, context) => { | |
// รับค่า base64 ที่ได้จาก LIFF app โดย split เพื่อตัด type ที่นำหน้าออก | |
const base64 = data.base64.split(",") | |
// import และ initial ตัว lib ของ Cloud Vision API | |
const vision = require('@google-cloud/vision') | |
const client = new vision.ImageAnnotatorClient() | |
// ส่งค่า base64 ไปให้ Cloud Vision API และรับค่าได้ที่กลับมา | |
const request = { image: { content: base64[1] } } | |
const [result] = await client.textDetection(request) | |
const detections = result.fullTextAnnotation.text | |
const datas = {} | |
// เอาผลลัพธ์ที่ได้มาตัดบรรทัดและ loop ออกมาทีละบรรทัด | |
detections.split('\n').forEach((row) => { | |
// ตัดข้อความในบรรทัดเป็นท่อนๆด้วย space | |
let items = row.split(' ') | |
// หาตัวเลขบัตรประชาชน | |
const thaiid = items.join('') | |
if (isThaiNationalID(thaiid)) { | |
datas.cardNumber = thaiid | |
} | |
// หาตำแหน่งของ คำนำหน้าชื่อ, ชื่อ และ นามสกุล | |
if (row.includes('ชื่อตัวและชื่อสกุล')) { | |
datas.prename = items[1] | |
datas.firstname = items[2] | |
datas.lastname = items[3] | |
} | |
// หาวันเดือนปีเกิด | |
if (row.includes('Date of Birth')) { | |
datas.birthDate = `${items[3]} ${items[4]} ${items[5]}` | |
} | |
}) | |
// เดาเพศสภาพจากคำนำหน้าชื่อ | |
if (datas.prename) { | |
datas.gender = 'M' | |
if (['น.ส.', 'นางสาว', 'นาง', 'เด็กหญิง'].includes(datas.prename)) { | |
datas.gender = 'F' | |
} | |
} | |
return { | |
result: datas | |
} | |
}) | |
// ฟังก์ชันสำหรับตรวจสอบความถูกต้องของเลขบัตรประชาชนแบบเบื้องต้น | |
function isThaiNationalID(id) { | |
if (!/^[0-9]{13}$/g.test(id)) { | |
return false | |
} | |
let i; let sum = 0 | |
for ((i = 0), (sum = 0); i < 12; i++) { | |
sum += Number.parseInt(id.charAt(i)) * (13 - i) | |
} | |
const checkSum = (11 - sum % 11) % 10 | |
if (checkSum === Number.parseInt(id.charAt(12))) { | |
return true | |
} | |
return false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment