Showing posts with label Lập trình. Show all posts
Showing posts with label Lập trình. Show all posts

Hôm nay mình hướng dẫn các bạn viết một ứng dụng nhỏ bằng python về nhận hiện khuôn mặt.

Yêu cầu: Nhận diện khuôn mặt bằng camera + xin chào "tên bạn"

Bước 1: Các bạn cài đặt python nhé, bản mình dùng trong ví dụ này là version 3.10.7. Chú ý khi cài nhớ cài đặt patch luôn nha.

Do mình cài rồi nên hiện như vầy á.

Bước 2: Traning model 
 - Các bạn vào đây nhé: https://teachablemachine.withgoogle.com/train/image
 - Các bạn up ảnh hoặc  sử dụng camera (Nếu không có thì dùng điện thoại làm camera cũng được ah)
 - Sau khi traning xong các bạn tải model về, nãy mình chưa lưu nên làm biếng chụp ảnh lại quá
 - Trên popup lưu model có chỗ copy code á, bạn copy đoạn code vô để làm hàm nhân diện (lười làm lại chỗ này, các bạn chút lấy code bên dưới cũng được)

Bước 3: Vào visual code tạo file nhandien.py (Hoặc bất kỳ IDE nào các bạn quen nha)
- Cài đặt một số thư viện chỗ import trong hình nhen.
- Chú ý là: mình dùng câu lệch #pip3 install ten-package để cài đặt

Cài đặt các thư viện trong import vô nhen

Code:
Hàm xin chào :
def speak(text):
    tts = gTTS(text = text, lang = language, slow = False)
    tts.save("sound.mp3")
    playsound.playsound("sound.mp3", True)
    os.remove("sound.mp3")

Hàm chụp ảnh từ cam và lưu lại với tên test.jpg :
camera = cv2.VideoCapture(0)
def capture_image():
    ret,frame = camera.read()
    if ret == True :
        cv2.imwrite('test.jpg',frame)

Hàm nhận diện khuôn mặt (Copy trên teachablemachine về nhen) có edit lại 1 chút.
def face_detaction():
    np.set_printoptions(suppress=True)
    # Load the model
    model = tf.keras.models.load_model('keras_model.h5')

    # Create the array of the right shape to feed into the keras model
    # The 'length' or number of images you can put into the array is
    # determined by the first position in the shape tuple, in this case 1.
    data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
    # Replace this with the path to your image
    image = Image.open('test.jpg')
    # resize the image to a 224x224 with the same strategy as in TM2:
    # resizing the image to be at least 224x224 and then cropping from the center
    size = (224, 224)
    image = ImageOps.fit(image, size, Image.ANTIALIAS)

    # turn the image into a numpy array
    image_array = np.asarray(image)
    # Normalize the image
    normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1
    # Load the image into the array
    data[0] = normalized_image_array

    # run the inference
    prediction = model.predict(data)
    print(prediction)

    name = ["Anh Nen", "Hoàng Duy"]
    index = 1
    max_value = -1
    for i in range(0, len(prediction[0])):
        if max_value < prediction[0][i]:
            max_value = prediction[0][i]
            index = i
    print("Result: ", name[index])
    print("Exactly: ", max_value)

    speak("Xin chào " + name[index] )

Gọi lại hàm:
while True:
    capture_image()
    face_detaction()


Các chú ý

1. Nếu bạn cài thư viện python không được do lỗi patch quá dài , thì vào chỉnh registry nhé

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem
Chỉnh về : 1

2. Lỗi không thể run puthon file ở Visual Studio Code
Vào Microsoft Store tải python hoặc set enviroment rồi log off lại máy




  

Khi tạo một project bằng Visual Studio, và bạn muốn đưa project này lên Git thì làm như sau:

Bước 1: tạo Git Repositories Online



Bước 2: Truy cập vào thư mục chứa project, nhấn chuột shift + chuột phải để mở power shell.



Thực hiện lần lượt các câu lệnh bên dưới.

  1. git init

  2. git remote add origin "Link Git mà bạn tạo ở bước 1"

  3. git remote -v (for checking current repository)

  4. git add -A(add all files)

  5. git commit -m 'Added my project'

  6. git pull --rebase origin master

  7. git push origin master



Mô tả lỗi: Routing vẫn chạy ngon lành dưới local nhưng khi public lên domain thì bị lỗi 404.

Rất có thể đó là do máy chủ web của bạn thực sự đang cố gắng tìm một trang tương ứng với URL. Tuy nhiên, vì ứng dụng Angular là một SPA nên các phần tử được đưa vào một trang động dựa trên url trong trình duyệt của bạn, do đó, khi yêu cầu routing, máy chủ sẽ trả về lỗi 404 HTTP. Điều này có thể được giải quyết bằng cách sử dụng HashLocationStrategy, gắn dấu # vào URL của bạn, giúp bạn có thể điều hướng khi ứng dụng được triển khai.


Cách khắc phục:
Mở app.module.ts :
Import thêm thư viện: import { HashLocationStrategy, LocationStrategy } from '@angular/common';
Thêm provider: providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}]









Các bước cấu hình

1. Cài đặt các gói cần thiết
#npm install --save ejs
#npm install --save bootstrap
#npm install --save jquery
#npm install --save popper

2. Tạo 1 thư mục views
- Folder: include : chưa cái file được xử dụng lại như : header, footer. nav
- 2 file: index.ejs, about.ejs
index.ejs
<!DOCTYPE html>
<html lang="en">
    <% include ('./include/head'%>
    <body>
        <% include ('./include/nav')  %>
        <div class="container">
            <div class="row">
            <h1>Home</h1>
            </div>
            <hr>
            <div class="row">
                <p style="height:300px;">Content Here...</p>
            </div>
        </div>
        <% include ('./include/scripts'%>
        <% include ('./include/footer'%>
    </body>
</html>
about.ejs
<!DOCTYPE html>
<html lang="en">
    <% include ('./include/head'%>
    <body>
        <% include ('./include/nav'%>
        <div class="container">
            <div class="row">
                <h1>About</h1>
            </div>
            <hr>
            <div class="row">
                <p style="height:300px;">Content Here...</p>
            </div>
        </div>
        <% include ('./include/scripts')  %>
        <% include ('./include/footer'%>
    </body>
</html>

Cầu hình app.js , do ở đây mình sử dụng chung để viết API nên sẽ cấu hình hơi khác.
const express = require('express')
const bodyParser = require('body-parser');
const path = require('path');
const app = express()

var port = process.env.HOST_PORT || 3300;
// Require static assets from public folder--------------------------- EJS
app.use(express.static(path.join(__dirname'public')));
// Set 'views' directory for any views 
// being rendered res.render()
app.set('views'path.join(__dirname'views'));
// Set view engine as EJS
app.engine('html'require('ejs').renderFile);
app.set('view engine''ejs');
//-------------------------------------------------------END EJS config
app.listen(port, () => {
    console.log("This port: " + port + " is running");
});

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var router = require('./routes')();
app.use('/'router);

//CORS Middleware
app.use(function (reqresnext) {
    //Enabling CORS 
    res.header("Access-Control-Allow-Origin""*");
    res.header("Access-Control-Allow-Methods""GET,HEAD,OPTIONS,POST,PUT");
    res.header("Access-Control-Allow-Headers""Origin, X-Requested-With, contentType,Content-Type, Accept, Authorization");
    next();
});

Tạo 1 file route.js
- Ở đây mình có require 2 file route, 1 cái của API , 1 cái của view. (API sẽ trình bày trong bày khác
const express = require('express'); 
function eRoutes() {
    const router = express.Router();
    var user = require('./routes/user.routes')(router);
    var view = require('./routes/view.routes')(router);
    return router;
}
module.exports = eRoutes;
Tạo 1 thư mục route, để chưa file route
Tạo 1 file view.route.js trong thư mục route

const express = require('express');
module.exports = function (router) {
    router.get('/', (reqres=> {
        console.log('Request for home recieved');
        res.render('index');
    });
    router.get('/about', (reqres=> {
        console.log('Request for about page recieved');
        res.render('about');
    });
    router.get('/contact', (reqres=> {
        console.log('Request for contact page recieved');
        res.render('contact');
    });
}

Xem kết quả nào:
Trang home

Trang About


  Bài viết hướng dẫn gửi thông báo vào group Telegram thông qua Bot API. các phần của bài viết

1. Tạo Bot Telegram

2. Tạo Group Telegram , ad bot và test gửi tin nhắn

3. Tạo API resfull với .net core và test bằng postman

I. TẠO BOT TRÊN TELEGRAM

Bước 1: Tìm BotFather tại ô tìm kiếm (Chú ý cái có tic xanh nhé)

Tìm BotFather

Bước 2: CLick "Start" để bắt đầu tạo Bot

Lệnh trên Bot

 - /newbot: Chọn tên cho Bot của bạn -> Chọn username cho Bot của bạn (Chú ý phải kết thúc bằng chữ "bot"
- Sau khi tạo xong Bot sẽ gửi cho bạn một Token, nhớ lưu lại để dùng gửi tin nhắn nhé.

Token mà bot gửi về


II. TẠO GROUP TELEGRAM - ADD BOT VÀ TEST
Bước 1: Tạo Group Telegram và add bot và group, chú ý coi chừng add nhằm bot nhé =))

Tạo group chat với Bot.


Bước 2 : Test thông báo 

 1. Lấy ID Bot và các group chat: https://api.telegram.org/bot<Token>/getUpdates 
(Chạy trên trình duyệt hoặc Postman đều đc nhé)
    
ID của Bot chat
ID của group chat

 2. Kiểm tra message trên Bot: https://api.telegram.org/bot<Token>/sendMessage?chat_id=<ID Chat>&text=<Message> (Chạy trên trình duyệt hoặc Postman đều đc nhé)
Thông báo trên bot

Thông báo trên group đã add bot


III. TẠO RESFUL API TRÊN .NET CORE 
  Bước 1: Tạo mới một project: API .Net Core



Bước 2: Tạo mới 1 Controller và test trên postman xem ok ko.
Bước 3: Tạo model chưa body Json và tạo 1 hàm post như bên dưới



Bước 4: test lại trên postman.




















 Have 2 ways validate form in angular.

First Way: Use FormBuilder

HTML file

 <form [formGroup]="angForm" novalidate>

<div class="form-group"> <label class="center-block">Name: <input class="form-control" formControlName="name"> </label> </div> <div *ngIf="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)" class="alert alert-danger"> <div *ngIf="angForm.controls['name'].errors.required"> Name is required. </div> </div> </form> <p>Form value: {{ angForm.value | json }}</p> <p>Form status: {{ angForm.status | json }}</p>

TS file

import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular Form Validation Tutorial'; angForm: FormGroup; constructor(private fb: FormBuilder) { this.createForm(); } createForm() { this.angForm = this.fb.group({ name: ['', Validators.required ] }); } }

Second Way: Use ngModel
Create model file class
    
export class ContactForm {
    constructor(
        public namestring,
        public emailstring,
        public subjectstring,
        public phone?: string,
        public content?: string
    ) { }
}

HTML File
<form (ngSubmit)="onSubmit()" #requestForm="ngForm" id="requestForm" name="requestForm">
    <div class="row">
        <div class="col-lg-6">
            <input class="form-control" type="text" name="name" value="" size="40" required minlength="2" appForbiddenName="admin"
            [(ngModel)]="model.name" #name="ngModel" #_name placeholder="(1) Họ tên *">
            
        </div>
        <div class="col-lg-6">
            <input class="form-control" type="email" name="email" #_email value="" size="40"
                aria-required="true" aria-invalid="false" placeholder="Email">
        </div>
        <div class="col-lg-6">
            <input class="form-control" type="text" name="subject" value="" size="40" required minlength="3" #_subject
                #subject="ngModel" [(ngModel)]="model.subject" aria-invalid="false" placeholder="(2) Tiêu đề *">
        </div>

        <div class="col-lg-6">
            <input class="form-control" type="text" name="phone" value="" size="40" required pattern="^\+?(?:[0-9]??).{5,14}[0-9]$" #_phone
                #phone="ngModel" [(ngModel)]="model.phone" aria-required="true" aria-invalid="false" placeholder="(3) Số điện thoại *">
        </div>
        <div class="col-xs-12">
            <textarea class="form-control" name="message" cols="40" rows="4" required #_message
            #message="ngModel" [(ngModel)]="model.content" aria-invalid="false" placeholder="(4) Nội dung bạn quan tâm *"></textarea>
        </div>
        <div class="col-xs-12">
            <input class="btn btn-primary" [disabled]="!requestForm.form.valid" type="submit" #submit_bt value="    Gửi    ">
        </div>
    </div>
</form>
<div>
    <p *ngIf="name.invalid && (name.dirty || name.touched)" class="alert alert-danger">
        <span *ngIf="name.errors.required">
            (1) Họ tên không được trống.
        </span>
        <span *ngIf="name.errors.minlength">
            (1) Tên ít nhất phải 2 ký tự.
        </span>
        <span *ngIf="name.errors.forbiddenName">
            (1) Tên bạn không thể là "admin".
        </span>
    </p>
    <p *ngIf="subject.invalid && (subject.dirty || subject.touched)" class="alert alert-danger">
        <span *ngIf="subject.errors.required">
            (2) Tiêu đề không được trống.
        </span>
        <span *ngIf="subject.errors.minlength">
            (2) Tiêu đề ít nhất phải 3 ký tự.
        </span>
    </p>
    <p *ngIf="phone.invalid && (phone.dirty || phone.touched)" class="alert alert-danger">
        <span *ngIf="phone.errors.required">
            (3) Số điện thoại không được trống.
        </span>
        <span *ngIf="phone.errors.pattern">
            (3) Điện thoại không đúng định dạng.
        </span>
    </p>
    <p *ngIf="message.invalid && (message.dirty || message.touched)" class="alert alert-danger">
        <span *ngIf="message.errors.required">
            (4) Nội dung không được trống.
        </span>
    </p>
</div>

TS File

import { Contact } from '../../Class/contact';
model = new Contact('','','','','');
  @ViewChild('_name', {static: true}) name: ElementRef;
  @ViewChild('_subject', {static: true}) subject: ElementRef;
  @ViewChild('_phone', {static: true}) phone: ElementRef;
  @ViewChild('_email', {static: true}) email:ElementRef;
  @ViewChild('_message', {static: true}) message: ElementRef;
  // @ViewChild('submit_bt',{static: true}) submit_bt: ElementRef;
  async onSubmit(){
    let _name = this.name.nativeElement.value;
    let _subject = this.subject.nativeElement.value;
    let _phone = this.phone.nativeElement.value;
    let _email = this.email.nativeElement.value;
    let _message = this.message.nativeElement.value;
    alert(_name + " - " + _subject + " - " + _phone + " - " + _email + " - " + _message)
  }

Không cần khai báo trong ts file, nhưng muốn lấy giá trị form cần dùng @ViewChild('Name',{static:true}) name:ElementRef;