亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Rendering
Home WeChat Applet WeChat Development Let's see how good you look! Public account developed based on Python

Let's see how good you look! Public account developed based on Python

Jul 25, 2018 pm 01:56 PM
python AI No public WeChat Micro-channel public platform

This is a Python-based WeChat public account development for appearance detection. Today we analyze the user's pictures through Tencent's AI platform and then return them to the user. Let’s experience the beauty test of public accounts together

Rendering

Lets see how good you look! Public account developed based on Python

Lets see how good you look! Public account developed based on Python

Lets see how good you look! Public account developed based on Python

##1. Access to Tencent AI platform

Let’s first take a look at the description of the official face detection and analysis interface:

Detect all faces (Face) in a given picture (Image) location and corresponding facial attributes. The position includes (x, y, w, h), and the facial attributes include gender, age, expression, beauty, glasses and posture (pitch, roll, yaw).

The request parameters include the following:

  • app_id application identification, we can get the app_id after registering on the AI ??platform

  • time_stamp timestamp

  • nonce_str random string

  • sign signature information, we need to calculate it ourselves

  • image Images to be detected (upper limit 1M)

  • mode Detection mode

1. Interface authentication, constructing request parameters

The official gave us the calculation method for interface authentication.

  1. Sort the request parameter pairs in ascending dictionary order by key to obtain an ordered list of parameter pairs N

  2. The parameter pairs in list N are spliced ??into strings in the format of URL key-value pairs to obtain string T (for example: key1=value1&key2=value2). The value part of the URL key-value splicing process requires URL encoding. The URL encoding algorithm uses capital letters. For example, instead of lowercase ?

  3. , use app_key as the key name of the application key to form a URL key value and splice it to the end of the string T to obtain the string S (such as: key1=value1&key2 =value2&app_key=Key)

  4. Perform MD5 operation on the string S, convert all characters of the obtained MD5 value into uppercase, and obtain the interface request signature

2. Request the interface address

Request the interface information. We use requests to send the request, and we will get the returned image information in json format.

pip install requestsInstall requests.

3. Process the returned information

Process the returned information, display the information on the picture, and then save the processed picture. Here we use opencv and pillow libraries

pip install pillow and pip install opencv-python to install.

Start writing code. We create a new face_id.py file to connect to the AI ??platform and return the detected image data.

import time
import random
import base64
import hashlib
import requests
from urllib.parse import urlencode
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont
import os


# 一.計算接口鑒權(quán),構(gòu)造請求參數(shù)

def random_str():
    '''得到隨機(jī)字符串nonce_str'''
    str = 'abcdefghijklmnopqrstuvwxyz'
    r = ''
    for i in range(15):
        index = random.randint(0,25)
        r += str[index]
    return r


def image(name):
    with open(name, 'rb') as f:
        content = f.read()
    return base64.b64encode(content)


def get_params(img):
    '''組織接口請求的參數(shù)形式,并且計算sign接口鑒權(quán)信息,
    最終返回接口請求所需要的參數(shù)字典'''
    params = {
        'app_id': '1106860829',
        'time_stamp': str(int(time.time())),
        'nonce_str': random_str(),
        'image': img,
        'mode': '0'

    }

    sort_dict = sorted(params.items(), key=lambda item: item[0], reverse=False)  # 排序
    sort_dict.append(('app_key', 'P8Gt8nxi6k8vLKbS'))  # 添加app_key
    rawtext = urlencode(sort_dict).encode()  # URL編碼
    sha = hashlib.md5()
    sha.update(rawtext)
    md5text = sha.hexdigest().upper()  # 計算出sign,接口鑒權(quán)
    params['sign'] = md5text  # 添加到請求參數(shù)列表中
    return params

# 二.請求接口URL


def access_api(img):
    frame = cv2.imread(img)
    nparry_encode = cv2.imencode('.jpg', frame)[1]
    data_encode = np.array(nparry_encode)
    img_encode = base64.b64encode(data_encode)  # 圖片轉(zhuǎn)為base64編碼格式
    url = 'https://api.ai.qq.com/fcgi-bin/face/face_detectface'
    res = requests.post(url, get_params(img_encode)).json()  # 請求URL,得到j(luò)son信息
    # 把信息顯示到圖片上
    if res['ret'] == 0:  # 0代表請求成功
        pil_img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))  # 把opencv格式轉(zhuǎn)換為PIL格式,方便寫漢字
        draw = ImageDraw.Draw(pil_img)
        for obj in res['data']['face_list']:
            img_width = res['data']['image_width']  # 圖像寬度
            img_height = res['data']['image_height']  # 圖像高度
            # print(obj)
            x = obj['x']  # 人臉框左上角x坐標(biāo)
            y = obj['y']  # 人臉框左上角y坐標(biāo)
            w = obj['width']  # 人臉框?qū)挾?            h = obj['height']  # 人臉框高度
            # 根據(jù)返回的值,自定義一下顯示的文字內(nèi)容
            if obj['glass'] == 1:  # 眼鏡
                glass = '有'
            else:
                glass = '無'
            if obj['gender'] >= 70:  # 性別值從0-100表示從女性到男性
                gender = '男'
            elif 50 <= obj[&#39;gender&#39;] < 70:
                gender = "娘"
            elif obj[&#39;gender&#39;] < 30:
                gender = &#39;女&#39;
            else:
                gender = &#39;女漢子&#39;
            if 90 < obj[&#39;expression&#39;] <= 100:  # 表情從0-100,表示笑的程度
                expression = &#39;一笑傾城&#39;
            elif 80 < obj[&#39;expression&#39;] <= 90:
                expression = &#39;心花怒放&#39;
            elif 70 < obj[&#39;expression&#39;] <= 80:
                expression = &#39;興高采烈&#39;
            elif 60 < obj[&#39;expression&#39;] <= 70:
                expression = &#39;眉開眼笑&#39;
            elif 50 < obj[&#39;expression&#39;] <= 60:
                expression = &#39;喜上眉梢&#39;
            elif 40 < obj[&#39;expression&#39;] <= 50:
                expression = &#39;喜氣洋洋&#39;
            elif 30 < obj[&#39;expression&#39;] <= 40:
                expression = &#39;笑逐顏開&#39;
            elif 20 < obj[&#39;expression&#39;] <= 30:
                expression = &#39;似笑非笑&#39;
            elif 10 < obj[&#39;expression&#39;] <= 20:
                expression = &#39;半嗔半喜&#39;
            elif 0 <= obj[&#39;expression&#39;] <= 10:
                expression = &#39;黯然傷神&#39;
            delt = h // 5  # 確定文字垂直距離
            # 寫入圖片
            if len(res[&#39;data&#39;][&#39;face_list&#39;]) > 1:  # 檢測到多個人臉,就把信息寫入人臉框內(nèi)
                font = ImageFont.truetype(&#39;yahei.ttf&#39;, w // 8, encoding=&#39;utf-8&#39;)  # 提前把字體文件下載好
                draw.text((x + 10, y + 10), &#39;性別 :&#39; + gender, (76, 176, 80), font=font)
                draw.text((x + 10, y + 10 + delt * 1), &#39;年齡 :&#39; + str(obj[&#39;age&#39;]), (76, 176, 80), font=font)
                draw.text((x + 10, y + 10 + delt * 2), &#39;表情 :&#39; + expression, (76, 176, 80), font=font)
                draw.text((x + 10, y + 10 + delt * 3), &#39;魅力 :&#39; + str(obj[&#39;beauty&#39;]), (76, 176, 80), font=font)
                draw.text((x + 10, y + 10 + delt * 4), &#39;眼鏡 :&#39; + glass, (76, 176, 80), font=font)
            elif img_width - x - w < 170:  # 避免圖片太窄,導(dǎo)致文字顯示不完全
                font = ImageFont.truetype(&#39;yahei.ttf&#39;, w // 8, encoding=&#39;utf-8&#39;)
                draw.text((x + 10, y + 10), &#39;性別 :&#39; + gender, (76, 176, 80), font=font)
                draw.text((x + 10, y + 10 + delt * 1), &#39;年齡 :&#39; + str(obj[&#39;age&#39;]), (76, 176, 80), font=font)
                draw.text((x + 10, y + 10 + delt * 2), &#39;表情 :&#39; + expression, (76, 176, 80), font=font)
                draw.text((x + 10, y + 10 + delt * 3), &#39;魅力 :&#39; + str(obj[&#39;beauty&#39;]), (76, 176, 80), font=font)
                draw.text((x + 10, y + 10 + delt * 4), &#39;眼鏡 :&#39; + glass, (76, 176, 80), font=font)
            else:
                font = ImageFont.truetype(&#39;yahei.ttf&#39;, 20, encoding=&#39;utf-8&#39;)
                draw.text((x + w + 10, y + 10), &#39;性別 :&#39; + gender, (76, 176, 80), font=font)
                draw.text((x + w + 10, y + 10 + delt * 1), &#39;年齡 :&#39; + str(obj[&#39;age&#39;]), (76, 176, 80), font=font)
                draw.text((x + w + 10, y + 10 + delt * 2), &#39;表情 :&#39; + expression, (76, 176, 80), font=font)
                draw.text((x + w + 10, y + 10 + delt * 3), &#39;魅力 :&#39; + str(obj[&#39;beauty&#39;]), (76, 176, 80), font=font)
                draw.text((x + w + 10, y + 10 + delt * 4), &#39;眼鏡 :&#39; + glass, (76, 176, 80), font=font)

            draw.rectangle((x, y, x + w, y + h), outline="#4CB050")  # 畫出人臉方框
            cv2img = cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2BGR)  # 把 pil 格式轉(zhuǎn)換為 cv
            cv2.imwrite(&#39;faces/{}&#39;.format(os.path.basename(img)), cv2img)  # 保存圖片到 face 文件夾下
            return &#39;檢測成功&#39;
    else:
        return &#39;檢測失敗&#39;

At this point our face detection interface access and image processing are completed. After receiving the picture information sent by the user, call this function and return the processed picture to the user.

Return the picture to the user

When receiving the user picture, the following steps are required:

Save the picture

After receiving the user picture, We need to save the image first, and then we can call the face analysis interface and transfer the image information. We need to write an img_download function to download the image. See the code below for details

Calling the face analysis interface

After downloading the image, call the interface function in the face_id.py file to get the processed image.

Upload pictures

The detection result is a new picture. To send the picture to the user, we need a Media_ID. To obtain the Media_ID, we must first upload the picture as a temporary material, so here we need An img_upload function is used to upload images, and an access_token is required when uploading. We obtain it through a function.

To obtain the access_token, we must add our own IP address to the whitelist, otherwise it will not be obtained. Please log in to "WeChat Public Platform-Development-Basic Configuration" to add the server IP address to the IP whitelist in advance. You can view the IP of this machine at http://ip.qq.com/...

Start writing code, we create a new utils.py to download and upload pictures

import requests
import json
import threading
import time
import os

token = &#39;&#39;
app_id = &#39;wxfc6adcdd7593a712&#39;
secret = &#39;429d85da0244792be19e0deb29615128&#39;


def img_download(url, name):
    r = requests.get(url)
    with open(&#39;images/{}-{}.jpg&#39;.format(name, time.strftime("%Y_%m_%d%H_%M_%S", time.localtime())), &#39;wb&#39;) as fd:
        fd.write(r.content)
    if os.path.getsize(fd.name) >= 1048576:
        return &#39;large&#39;
    # print(&#39;namename&#39;, os.path.basename(fd.name))
    return os.path.basename(fd.name)


def get_access_token(appid, secret):
    &#39;&#39;&#39;獲取access_token,100分鐘刷新一次&#39;&#39;&#39;

    url = &#39;https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}&#39;.format(appid, secret)
    r = requests.get(url)
    parse_json = json.loads(r.text)
    global token
    token = parse_json[&#39;access_token&#39;]
    global timer
    timer = threading.Timer(6000, get_access_token)
    timer.start()


def img_upload(mediaType, name):
    global token
    url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s" % (token, mediaType)
    files = {&#39;media&#39;: open(&#39;{}&#39;.format(name), &#39;rb&#39;)}
    r = requests.post(url, files=files)
    parse_json = json.loads(r.text)
    return parse_json[&#39;media_id&#39;]

get_access_token(app_id, secret)

Return to the user

We simply modify the logic after receiving the picture, after receiving the picture Face detection, upload to obtain Media_ID, all we have to do is return the image to the user. Directly look at the code of connect.py

import falcon
from falcon import uri
from wechatpy.utils import check_signature
from wechatpy.exceptions import InvalidSignatureException
from wechatpy import parse_message
from wechatpy.replies import TextReply, ImageReply

from utils import img_download, img_upload
from face_id import access_api


class Connect(object):

    def on_get(self, req, resp):
        query_string = req.query_string
        query_list = query_string.split(&#39;&&#39;)
        b = {}
        for i in query_list:
            b[i.split(&#39;=&#39;)[0]] = i.split(&#39;=&#39;)[1]

        try:
            check_signature(token=&#39;lengxiao&#39;, signature=b[&#39;signature&#39;], timestamp=b[&#39;timestamp&#39;], nonce=b[&#39;nonce&#39;])
            resp.body = (b[&#39;echostr&#39;])
        except InvalidSignatureException:
            pass
        resp.status = falcon.HTTP_200

    def on_post(self, req, resp):
        xml = req.stream.read()
        msg = parse_message(xml)
        if msg.type == &#39;text&#39;:
            reply = TextReply(content=msg.content, message=msg)
            xml = reply.render()
            resp.body = (xml)
            resp.status = falcon.HTTP_200
        elif msg.type == &#39;image&#39;:
            name = img_download(msg.image, msg.source)  # 下載圖片
            r = access_api(&#39;images/&#39; + name)
            if r == &#39;檢測成功&#39;:
                media_id = img_upload(&#39;image&#39;, &#39;faces/&#39; + name)  # 上傳圖片,得到 media_id
                reply = ImageReply(media_id=media_id, message=msg)
            else:
                reply = TextReply(content=&#39;人臉檢測失敗,請上傳1M以下人臉清晰的照片&#39;, message=msg)
            xml = reply.render()
            resp.body = (xml)
            resp.status = falcon.HTTP_200

app = falcon.API()
connect = Connect()
app.add_route(&#39;/connect&#39;, connect)

Now our work is done, and our official account can be tested for appearance. I originally planned to use it on my official account, but there are still several problems below, so I didn’t use it.

  1. WeChat’s mechanism, our program must respond within 5s. Otherwise, it will report 'The service provided by the official account is faulty'. However, image processing is sometimes slow, often exceeding 5 seconds. Therefore, the correct processing method should be to return an empty string immediately after receiving the user's request to indicate that we have received it, and then create a separate thread to process the image. When the image is processed, it is sent to the user through the customer service interface. Unfortunately, uncertified public accounts do not have a customer service interface, so there is nothing you can do. If it takes more than 5 seconds, an error will be reported.

  2. The menu cannot be customized. Once custom development is enabled, the menu also needs to be customized. However, uncertified official accounts do not have permission to configure the menu through the program and can only configure it in the WeChat background. configuration.

So, I have not enabled this program on my official account, but if you have a certified official account, you can try to develop various fun functions.

Related recommendations:

WeChat public platform development One-click follow WeChat public platform account

WeChat public platform development attempt, WeChat public platform

Video: Chuanzhi and Dark Horse WeChat public platform development video tutorial

The above is the detailed content of Let's see how good you look! Public account developed based on Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
How to use PHP to build social sharing functions PHP sharing interface integration practice How to use PHP to build social sharing functions PHP sharing interface integration practice Jul 25, 2025 pm 08:51 PM

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

PHP calls AI intelligent voice assistant PHP voice interaction system construction PHP calls AI intelligent voice assistant PHP voice interaction system construction Jul 25, 2025 pm 08:45 PM

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization Jul 25, 2025 pm 08:57 PM

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism Jul 25, 2025 pm 08:30 PM

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

python seaborn jointplot example python seaborn jointplot example Jul 26, 2025 am 08:11 AM

Use Seaborn's jointplot to quickly visualize the relationship and distribution between two variables; 2. The basic scatter plot is implemented by sns.jointplot(data=tips,x="total_bill",y="tip",kind="scatter"), the center is a scatter plot, and the histogram is displayed on the upper and lower and right sides; 3. Add regression lines and density information to a kind="reg", and combine marginal_kws to set the edge plot style; 4. When the data volume is large, it is recommended to use "hex"

How to build a content payment platform through PHP How to implement PHP paid reading system How to build a content payment platform through PHP How to implement PHP paid reading system Jul 25, 2025 pm 06:30 PM

To build a PHP content payment platform, it is necessary to build a user management, content management, payment and permission control system. First, establish a user authentication system and use JWT to achieve lightweight authentication; second, design the backend management interface and database fields to manage paid content; third, integrate Alipay or WeChat payment and ensure process security; fourth, control user access rights through session or cookies. Choosing the Laravel framework can improve development efficiency, use watermarks and user management to prevent content theft, optimize performance requires coordinated improvement of code, database, cache and server configuration, and clear policies must be formulated and malicious behaviors must be prevented.

PHP integrated AI emotional computing technology PHP user feedback intelligent analysis PHP integrated AI emotional computing technology PHP user feedback intelligent analysis Jul 25, 2025 pm 06:54 PM

To integrate AI sentiment computing technology into PHP applications, the core is to use cloud services AIAPI (such as Google, AWS, and Azure) for sentiment analysis, send text through HTTP requests and parse returned JSON results, and store emotional data into the database, thereby realizing automated processing and data insights of user feedback. The specific steps include: 1. Select a suitable AI sentiment analysis API, considering accuracy, cost, language support and integration complexity; 2. Use Guzzle or curl to send requests, store sentiment scores, labels, and intensity information; 3. Build a visual dashboard to support priority sorting, trend analysis, product iteration direction and user segmentation; 4. Respond to technical challenges, such as API call restrictions and numbers

python list to string conversion example python list to string conversion example Jul 26, 2025 am 08:00 AM

String lists can be merged with join() method, such as ''.join(words) to get "HelloworldfromPython"; 2. Number lists must be converted to strings with map(str, numbers) or [str(x)forxinnumbers] before joining; 3. Any type list can be directly converted to strings with brackets and quotes, suitable for debugging; 4. Custom formats can be implemented by generator expressions combined with join(), such as '|'.join(f"[{item}]"foriteminitems) output"[a]|[

See all articles