Python Intelligent Speech Recognition Language Translation Platform|Project Backend Construction

Basics of Python programming, use of third-party libraries such as Django, requests, hashlib, pyttsx3, etc., and introduction of Baidu API speech recognition business interface, text reading business interface, and translation business interface.

 

01,Task implementation steps

Task description: This task uses the Django framework to build the backend of an intelligent speech recognition and translation platform, including recognition, translation, and reading of Baidu API interface calls and all logic of the platform.

The first step: writing views.py. The Chinese-English translation interface requires input parameters as shown in Figure 1.

■Figure 1 Baidu api translation interface needs to pass in parameters

The core code of the Chinese-English translation interface is as follows.

#编写中英文翻译接口功能函数
def translate(text):
    appid = '20220826001320772'
    secretKey = 'C0jtrN2cmdIzVqIA_nsD'  # 填写你的密钥
    #按照pid文档编写(接入接口)
    httpClient = None
    myurl = '/api/trans/vip/translate'
    #翻译样式
    fromLang = 'auto'  #选择自动识别语言
    toLang = 'zh'      #翻译成中文
    salt = random.randint(32768, 65536)
    q = text
    sign = appid + q + str(salt) + secretKey
    sign = hashlib.md5(sign.encode()).hexdigest()
    myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(
    salt) + '&sign=' + sign
    #使用try语句处理异常
    try:
        httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
        httpClient.request('GET', myurl)

        # response是HTTPResponse对象
        response = httpClient.getresponse()
        result_all = response.read().decode("utf-8")
        result = json.loads(result_all)
        print(result)
        res = result['trans_result'][0]['dst']
        return ress
    except Exception as e:
        print (e)
    finally:
        if httpClient:
            httpClient.close()

 Step 2: Write routing urls.py. Establish a correspondence between the URL request and the views.py function that handles the request. The core code of the URL is as follows.


urlpatterns = [
    path('admin/', admin.site.urls),
    re_path('^voice/(?P<path>.*)',serve,{"document_root":MEDIA_ROOT}),
    re_path(r'^base/', include( 'base.urls', namespace="base") ),
    re_path(r'^onto/', include('ontology.urls', namespace="ontology")),
    re_path(r'^corpus/', include( 'corpus.urls', namespace="corpus") ),
    re_path(r'^event/', include('event.urls', namespace="event")),
    re_path(r'^txtproc/', include( 'txtproc.urls', namespace="txtproc") ),
    re_path(r'^lexicon/', include('lexicon.urls', namespace="lexicon")),
    re_path(r'^phrase/', include('phrase.urls', namespace="phrase")),
    re_path(r'^path/', include('path.urls', namespace="path")),
    re_path(r'^nlpapi/', include('nlpapi.urls', namespace="nlpapi")),
    re_path(r'^uapi/', include('utils.urls', namespace="uapi")),

 Step 3: Writing settings.py. settings.py is used to configure and manage the management and operation information of the Django project. The core code of settings.py is as follows.

#调试模式,创建工程后初始值为True
DEBUG=True
#ALLOWED_HOSTS用来设置允许哪些主机访问我们的django后台站点
ALLOWED_HOSTS = ['*']

# 核心代码放在apps上
sys.path.insert(0,os.path.join(BASE_DIR,'apps'))
INSTALLED_APPS = [
    'django.contrib.admin',             #内置的后台管理系统
    'django.contrib.auth',              #内置的用户认证系统
    'django.contrib.contenttypes',      #记录项目中所有model元数据
    'django.contrib.sessions',          #用于标识当前访问网站的用户身份,记录相关用户信息
    'django.contrib.messages',          #massage提示功能
    'django.contrib.staticfiles',       #查找静态资源路径
    'voice2voice'
]

#中间件MIDDLEWARE配置
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
#指定urls.py(路由)的路径,调用v2vservice中的类模块
ROOT_URLCONF = 'aitrans.urls'
#模板信息配置
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',  #定义模板引擎,用于识别模板里面的变量和指令
        'DIRS': [os.path.join(BASE_DIR,'templates')],            #指向模板存放的路径—templates文件夹,方便调用index.htm以及更高配置的base.htm
        'APP_DIRS': True,        #是否在App里查找模板文件
        #用于填充在RequestContext的上下文
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.media',
            ],
            'builtins':['django.templatetags.static'], #import static tag
        },
    },
]

WSGI_APPLICATION = 'aitrans.wsgi.application'

# Database——系统默认分配的数据库部分
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path

 Step 4: Writing wsgi.py. wsgi is the Web server gateway interface, which is actually a protocol. It complies with the WSGI protocol and is responsible for the implementation of the network communication part. The code of wsgi.py is as follows.


import os      #导入os库
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'aitrans.settings')
application = get_wsgi_application()

 Step 5: Start writing the main program manage.py. manage.py is as follows.

import sys
import os
#定义main()函数
def main():
    #调用settings.py
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'aitrans.settings')    
    #处理异常捕获
    try:                     
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)
#启动主程序
if __name__ == '__main__':
    main()

Guess you like

Origin blog.csdn.net/qq_41640218/article/details/134820024