在云服务器上部署简单的聊天机器人网站(源1.0接口版)

诸神缄默不语-个人CSDN博文目录

又不是不能用.jpg
http://47.113.197.198:8000/chat
在这里插入图片描述

集成代码可参考:花月与剑/scholar_ease

之所以先用源1.0,一是因为我API都申请了,不用白不用;二是因为源1.0可以直接用国内网络连接,所以分享过程中没有法律风险。

文章目录

  • 1. 安装环境配置
  • 2. 前后台代码编写
  • 3. 未完成的工作
  • 4. 其他参考资料

1. 安装环境配置

  1. 白嫖了阿里云的学生计划服务器:https://developer.aliyun.com/plan/student
    这个只要用支付宝认证学生就可以直接获得1个月的免费云服务器,然后完成一个非常简单的课程与考试就能再获得6个月的。
  2. 先按照这个教程开一下远程登录服务器的账号和密码:通过密码或密钥认证登录Linux实例
  3. 根据这个教程(Linux系统实例快速入门)的步骤2和4设置开一下端口和Apache服务
  4. 我个人习惯用VSCode,所以我就是用VSCode连的。可以用ssh,也可以用账号密码直接登录root账号
  5. 然后开一个新的用户账号:
    useradd user_name
    设置密码
  6. 之所以不能直接用root,是因为Apache不能用root账号,否则会报错:Error:\tApache has not been designed to serve pages while\n\trunning as root. There are known race conditions that\n\twill allow any local user to read any file on the system.\n\tIf you still desire to serve pages as root then\n\tadd -DBIG_SECURITY_HOLE to the CFLAGS env variable\n\tand then rebuild the server.\n\tIt is strongly suggested that you instead modify the User\n\tdirective in your httpd.conf file to list a non-root\n\tuser.\n
  7. 用新账号进/home/user_name,新建虚拟环境:
pip3 install --user pipx
python -m pipx install virtualenv
python -m pipx ensurepath
cd 放包的路径
virtualenv venv_name
source bin/activate
  1. 安装所需要的工具包:
pip install flask
yum -y install httpd-devel
sudo yum makecache
pip install mod_wsgi
pip install pytz
pip install requests
yum install tmux
  1. 配置Apache端口转发(但这玩意得有域名了才用得上,但我的域名还没有备案):Apache如何配置端口转发_linux 的 apache 如何端口跳转_Leon Jens的博客-CSDN博客 apache 80端口转发 - 掘金 apache配置端口转发的具体方法-Apache-PHP中文网 配置文件(httpd.conf)的路径及辅助配置文件的读取 | Apache Apache配置文件httpd.conf详解 - 简书 CentOS 7 Apache httpd 管理 - 阿笨哥

2. 前后台代码编写

测试时直接运行get_input.py,正式上线时在tmux中挂起mod_wsgi-express start-server wsgi.py --processes 4
(如果想调整端口,设置port参数1

get_input.py

from flask import Flask,request,render_template
from chatbot_reply import yuan10_result
import datetime,json

app = Flask(__name__)

today_date=datetime.datetime.today()

@app.route("/")
def get_home():
    return "Hello world"

@app.route('/chat',methods={'GET','POST'})
def chat():
    if request.method=='POST':
        total_yuan10_remain=((today_date-datetime.datetime.strptime('2023-5-26',"%Y-%m-%d")).days+1)*323  #放在前面似乎会导致不每天更新的问题

        if json.load(open('counter.json'))['yuan1.0_used']>total_yuan10_remain:
            return render_template('chat.html',chat_output='今天的试用次数已到达上限,请明日再来!',
                                   remain_token_counter=total_yuan10_remain-json.load(open('counter.json'))['yuan1.0_used'])
        
        user_input=request.form['user_input']
        counter=json.load(open('counter.json'))
        counter['yuan1.0_used']+=1
        json.dump(counter,open('counter.json','w'),ensure_ascii=False)
        return render_template('chat.html',chat_output='回复:'+yuan10_result(user_input),
                               remain_token_counter=total_yuan10_remain-json.load(open('counter.json'))['yuan1.0_used'])
    else:
        return render_template('chat.html',remain_token_counter=total_yuan10_remain-json.load(open('counter.json'))['yuan1.0_used'])

if __name__ == "__main__":
    app.run()

wsgi.py

from get_input import app

application = app

chatbot_reply/yuan10.py

from datetime import datetime
import pytz,os,hashlib,requests,json,time,uuid

SUBMIT_URL = "http://api-air.inspur.com:32102/v1/interface/api/infer/getRequestId?"
REPLY_URL = "http://api-air.inspur.com:32102/v1/interface/api/result?"

def code_md5(str):
    code=str.encode("utf-8")
    m = hashlib.md5()
    m.update(code)
    result= m.hexdigest()
    return result

def header_generation():
    """Generate header for API request."""
    t = datetime.now(pytz.timezone("Asia/Shanghai")).strftime("%Y-%m-%d")
    global ACCOUNT, PHONE
    ACCOUNT, PHONE = os.environ.get('YUAN_ACCOUNT').split('||')
    token=code_md5(ACCOUNT+PHONE+t)
    headers = {'token': token}
    return headers

def rest_get(url, header,timeout, show_error=False):
    '''Call rest get method'''
    try:
        response = requests.get(url, headers=header,timeout=timeout, verify=False)
        return response
    except Exception as exception:
        if show_error:
            print(exception)
        return None

def submit_request(query,temperature,topP,topK,max_tokens,engine, frequencyPenalty,responsePenalty,noRepeatNgramSize):
    """Submit query to the backend server and get requestID."""
    headers=header_generation()
    url=SUBMIT_URL + "engine={0}&account={1}&data={2}&temperature={3}&topP={4}&topK={5}&tokensToGenerate={6}" \
                     "&type={7}&frequencyPenalty={8}&responsePenalty={9}&noRepeatNgramSize={10}".\
        format(engine,ACCOUNT,query,temperature,topP,topK, max_tokens,"api", frequencyPenalty,responsePenalty,noRepeatNgramSize)
    response=rest_get(url,headers,30)
    response_text = json.loads(response.text)
    if  response_text["flag"]:
        requestId = response_text["resData"]
        return requestId
    else:
        raise  RuntimeWarning(response_text)

def reply_request(requestId,cycle_count=5):
    """Check reply API to get the inference response."""
    url = REPLY_URL + "account={0}&requestId={1}".format(ACCOUNT, requestId)
    headers=header_generation()
    response_text= {"flag":True, "resData":None}
    for i in range(cycle_count):
        response = rest_get(url, headers, 30, show_error=True)
        response_text = json.loads(response.text)
        if response_text["resData"] != None:
            return response_text
        if response_text["flag"] == False and i ==cycle_count-1:
            raise  RuntimeWarning(response_text)
        time.sleep(3)
    return response_text

#Yuan类
class Yuan:
    """The main class for a user to interface with the Inspur Yuan API.
    A user can set account info and add examples of the API request.
    """

    def __init__(self, 
                engine='base_10B',
                temperature=0.9,
                max_tokens=100,
                input_prefix='',
                input_suffix='\n',
                output_prefix='答:',
                output_suffix='\n\n',
                append_output_prefix_to_query=False,
                topK=1,
                topP=0.9,
                frequencyPenalty=1.2,
                responsePenalty=1.2,
                noRepeatNgramSize=2):
        
        self.examples = {}
        self.engine = engine
        self.temperature = temperature
        self.max_tokens = max_tokens
        self.topK = topK
        self.topP = topP
        self.frequencyPenalty = frequencyPenalty
        self.responsePenalty = responsePenalty
        self.noRepeatNgramSize = noRepeatNgramSize
        self.input_prefix = input_prefix
        self.input_suffix = input_suffix
        self.output_prefix = output_prefix
        self.output_suffix = output_suffix
        self.append_output_prefix_to_query = append_output_prefix_to_query
        self.stop = (output_suffix + input_prefix).strip()

    def add_example(self, ex):
        """Add an example to the object.
        Example must be an instance of the Example class."""
        assert isinstance(ex, Example), "Please create an Example object."
        self.examples[ex.get_id()] = ex

    def delete_example(self, id):
        """Delete example with the specific id."""
        if id in self.examples:
            del self.examples[id]

    def get_example(self, id):
        """Get a single example."""
        return self.examples.get(id, None)

    def get_all_examples(self):
        """Returns all examples as a list of dicts."""
        return {k: v.as_dict() for k, v in self.examples.items()}

    def get_prime_text(self):
        """Formats all examples to prime the model."""
        return "".join(
            [self.format_example(ex) for ex in self.examples.values()])

    def get_engine(self):
        """Returns the engine specified for the API."""
        return self.engine

    def get_temperature(self):
        """Returns the temperature specified for the API."""
        return self.temperature

    def get_max_tokens(self):
        """Returns the max tokens specified for the API."""
        return self.max_tokens

    def craft_query(self, prompt):
        """Creates the query for the API request."""
        q = self.get_prime_text(
        ) + self.input_prefix + prompt + self.input_suffix
        if self.append_output_prefix_to_query:
            q = q + self.output_prefix

        return q

    def format_example(self, ex):
        """Formats the input, output pair."""
        return self.input_prefix + ex.get_input(
        ) + self.input_suffix + self.output_prefix + ex.get_output(
        ) + self.output_suffix
    
    def response(self, 
                query,
                engine='base_10B',
                max_tokens=20,
                temperature=0.9,
                topP=0.1,
                topK=1,
                frequencyPenalty=1.0,
                responsePenalty=1.0,
                noRepeatNgramSize=0):
        """Obtains the original result returned by the API."""

        try:
            # requestId = submit_request(query,temperature,topP,topK,max_tokens, engine)
            requestId = submit_request(query, temperature, topP, topK, max_tokens, engine, frequencyPenalty,
                                       responsePenalty, noRepeatNgramSize)
            response_text = reply_request(requestId)
        except Exception as e:
            raise e
        
        return response_text


    def del_special_chars(self, msg):
        special_chars = ['<unk>', '<eod>', '#', '▃', '▁', '▂', ' ']
        for char in special_chars:
            msg = msg.replace(char, '')
        return msg


    def submit_API(self, prompt, trun=[]):
        """Submit prompt to yuan API interface and obtain an pure text reply.
        :prompt: Question or any content a user may input.
        :return: pure text response."""
        query = self.craft_query(prompt)
        res = self.response(query,engine=self.engine,
                            max_tokens=self.max_tokens,
                            temperature=self.temperature,
                            topP=self.topP,
                            topK=self.topK,
                            frequencyPenalty = self.frequencyPenalty,
                            responsePenalty = self.responsePenalty,
                            noRepeatNgramSize = self.noRepeatNgramSize)
        if 'resData' in res and res['resData'] != None:
            txt = res['resData']
        else:
            txt = '模型返回为空,请尝试修改输入'
        # 单独针对翻译模型的后处理
        if self.engine == 'translate':
            txt = txt.replace(' ##', '').replace(' "', '"').replace(": ", ":").replace(" ,", ",") \
                .replace('英文:', '').replace('文:', '').replace("( ", "(").replace(" )", ")")
        else:
            txt = txt.replace(' ', '')
        txt = self.del_special_chars(txt)

        # trun多结束符截断模型输出
        if isinstance(trun, str):
            trun = [trun]
        try:
            if trun != None and isinstance(trun, list) and  trun != []:
                for tr in trun:
                    if tr in txt and tr!="":
                        txt = txt[:txt.index(tr)]
                    else:
                        continue
        except:
            return txt
        return txt

def set_yuan_account(user, phone):
    os.environ['YUAN_ACCOUNT'] = user + '||' + phone

class Example:
    """ store some examples(input, output pairs and formats) for few-shots to prime the model."""
    def __init__(self, inp, out):
        self.input = inp
        self.output = out
        self.id = uuid.uuid4().hex

    def get_input(self):
        """return the input of the example."""
        return self.input

    def get_output(self):
        """Return the output of the example."""
        return self.output

    def get_id(self):
        """Returns the unique ID of the example."""
        return self.id

    def as_dict(self):
        return {
            "input": self.get_input(),
            "output": self.get_output(),
            "id": self.get_id(),
        }

# 1. set account
set_yuan_account("user_name", "mobile_phone")

yuan = Yuan(input_prefix="对话:“",
            input_suffix="”",
            output_prefix="答:“",
            output_suffix="”",
            max_tokens=300)
# 3. add examples if in need.
#yuan.add_example(Example(inp="我有10元钱,花了1元钱,我还剩多少钱?",
#                        out="9元"))

def yuan10_result(prompt,trun="”"):
    return yuan.submit_API(prompt,trun)[1:]

templates/chat.html

<!DOCTYPE html>
<html>
<body>

<h2>Chat with 源1.0</h2>
每天晚21:00左右更新网页,会有一段时间不能用
今日剩余使用次数:{{remain_token_counter}}

<form action="/chat" method="post">
  <label for="user_input">请输入您想问源1.0的内容:</label><br>
  <input type="text" id="user_input" name="user_input"><br>
  <input type="submit" value="Submit">
</form>

<p>{{ chat_output }}</p>

</body>
</html>

3. 未完成的工作

  1. 备案:https://beian.aliyun.com/
  2. 数据库
  3. 登录功能

4. 其他参考资料

  1. gcc: fatal error: cannot read spec file ‘/usr/lib/rpm/redhat/redhat-hardened-cc1 · Issue #167 · chrippa/ds4drv
  2. c++ - G++ error:/usr/lib/rpm/redhat/redhat-hardened-cc1: No such file or directory - Stack Overflow
  3. How To Install redhat-rpm-config on CentOS 7 | Installati.one
  4. Apache mod_wsgi模块简介_易生一世的博客-CSDN博客
  5. python - Could not find a version that satisfies the requirement - Stack Overflow
  6. Python3.5.1 => RuntimeError: The ‘apxs’ command appears not to be installed or is not executable · Issue #136 · GrahamDumpleton/mod_wsgi
  7. https://pypi.org/project/mod-wsgi/
  8. mod_wsgi — Flask Documentation (2.2.x)
  9. 偷个懒,公号抠腚早报80%自动化——3.Flask速成大法(上)-阿里云开发者社区
  10. 2021-11-16 flask部署在windows云服务器上进行公网访问_flask外网访问本地server_初冬的早晨的博客-CSDN博客
  11. Flask 报错:WARNING: This is a development server. Do not use it in a production deployment._吴家健ken的博客-CSDN博客
  12. 将flask程序部署在apache上_flask部署到apache_小鹰丶的博客-CSDN博客
  13. 第 3 章:模板 - Flask 入门教程
  14. Python:Flask简单实现统计网站访问量_python统计网站访问量_wangzirui32的博客-CSDN博客:也是本网站中采用的方案
  15. flask 计数器_afn2826的博客-CSDN博客:只能维持在session内
  16. command-not-found.com – tmux

  1. mod_wsgi-express start-server -h ↩︎

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/25783.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Vue登录界面精美模板分享

文章目录 &#x1f412;个人主页&#x1f3c5;Vue项目常用组件模板仓库&#x1f4d6;前言&#xff1a;&#x1f380;源码如下&#xff1a; &#x1f412;个人主页 &#x1f3c5;Vue项目常用组件模板仓库 &#x1f4d6;前言&#xff1a; 本篇博客主要提供vue组件之登陆组件源码…

idea连接Linux服务器

一、 介绍 配置idea的ssh会话和sftp可以实现对linux远程服务器的访问和文件上传下载&#xff0c;是替代Xshell的理想方式。这样我们就能在idea里面编写文件并轻松的将文件上传到linux服务器中。而且还能远程编辑linux服务器上的文件。掌握并熟练使用&#xff0c;能够大大提高我…

操作系统复习2.4.0-死锁详解

什么是死锁 各进程互相竞争对手里的资源&#xff0c;导致各进程都阻塞&#xff0c;都无法向前推进 死锁、饥饿、死循环的区别 死锁&#xff1a;各进程互相持有对方想要的资源且不释放&#xff0c;导致各进程阻塞&#xff0c;无法向前推进 饥饿&#xff1a;由于长期得不到想要…

四站精彩回顾 | Fortinet Accelerate 2023·中国区巡展火热进行中

Fortinet Accelerate 2023中国区巡展 上周&#xff0c;Fortinet Accelerate 2023中国区巡展分别走过青岛、南京、长沙、合肥四站&#xff0c;Fortinet携手太平洋电信、亚马逊云科技、中企通信等云、网、安合作伙伴&#xff0c;与各行业典型代表客户&#xff0c;就网安融合、网…

电动葫芦无法运转怎么办?

有关电动葫芦无法起动与运转故障&#xff0c;电动葫芦无法起动怎么办&#xff0c;有没有好的解决办法&#xff0c;检查电源熔丝是否烧断&#xff0c;定子绕组相间短路、接地或断路&#xff0c;以及是否负载过大或传动机械故障等。 电动葫芦无法运转故障怎么办 1、首先&#xf…

C语言基础习题讲解

C语言基础习题讲解 运算符判断简单循环 运算符 1. 设计一个程序, 输入三位数a, 分别输出个,十,百位. (0<a<1000) 样例输入: 251 样例输出: 2 5 1 #include <stdio.h> int main() {int input 0;int x 0;int y 0;int z 0;scanf("%d", &input);x …

7 种常见的路由协议

网络路由是网络通信的重要组成部分&#xff0c;通过互联网将信息从源地址移动到目的地的过程。路由发生在 OSI 模型的第 3 层&#xff08;网络层&#xff09;。实际网络中通常会将静态和动态路由结合使用。静态路由适用于小型网络&#xff0c;而动态路由适用于大型网络。 什么…

界面控件DevExpress ASP.NET新主题——Office 365暗黑主题的应用

DevExpress ASP.NET Web Forms Controls拥有针对Web表单&#xff08;包括报表&#xff09;的110种UI控件&#xff0c;DevExpress ASP.NET MVC Extensions是服务器端MVC扩展或客户端控件&#xff0c;由轻量级JavaScript小部件提供支持的70个高性能DevExpress ASP.NET Core Contr…

华为路由器 IPSec VPN 配置

需求&#xff1a; 通过 IPSecVPN 实现上海与成都内网互通 拓扑图如下&#xff1a; 一、首先完成网络配置 1、R1 路由器设置 <Huawei>sys [Huawei]sys R1 [R1]un in en# 开启DHCP [R1]dhcp enable# 设置内网接口 [R1]int g0/0/0 [R1-GigabitEthernet0/0/0]ip addr 10.…

Git日常使用技巧 - 笔记

Git日常使用技巧 - 笔记 Git是目前世界上最先进的分布式版本控制系统 学习资料 廖雪峰 学习视频 https://www.bilibili.com/video/BV1pX4y1S7Dq/?spm_id_from333.337.search-card.all.click&vd_source2ac127043ccd79c92d5b966fd4a54cd7 Git 命令在线练习工具 https://l…

国内可用 ChatGPT 网页版

前言 ChatGPT持续火热&#xff0c;然鹅国内很多人还是不会使用。 2023年6月1日消息&#xff0c;ChatGPT 聊天机器人可以根据用户的输入生成各种各样的文本&#xff0c;包括代码。但是&#xff0c;加拿大魁北克大学的四位研究人员发现&#xff0c;ChatGPT 生成的代码往往存在严…

项目开发-依赖倒置、里式替换、接口隔离的应用深入理解

文章目录 前言依赖倒置定义不符合依赖倒置原则是什么样子&#x1f604;完善 里式替换定义具体应用 接口隔离定义具体应用 前言 最近在做.net项目和学习这个设计模式中的依赖倒置和工厂方法&#xff0c;这个过程当中发现在开发这个.net项目中有很多不合理的地方&#xff0c;就是…

cplex基础入门(一)

这边文章会以纯新手小白的视角&#xff0c;教会大家如何快速的搭建自己的cplex模型&#xff0c;做到求解模型不求人。 目录 一、引言 1、掌握数据类型及数据结构 2、常规Cplex编程方法 3、Cplex编程步骤 4、cplex 程序框架 5、创建模型 二、规划建模的入门求解案例 1、…

Python3数据分析与挖掘建模(3)探索性数据分析

1. 概述 探索性数据分析&#xff08;Exploratory Data Analysis&#xff0c;EDA&#xff09;是一种数据分析的方法&#xff0c;用于探索和理解数据集的特征、关系和分布等。EDA旨在揭示数据中的模式、异常值、缺失值等信息&#xff0c;并为后续的分析和建模提供基础。以下是关…

CISCN 2023 初赛 pwn——Shellwego 题解

这是一个用go语言写的elf程序&#xff0c;没有PIE。这也是本蒟蒻第一次解go pwn题&#xff0c;故在此记录以便参考。 而且&#xff0c;这还是一个全部符号表被抠的go elf&#xff0c;直接面对一堆不知名的函数实在有些应付不来&#xff0c;因此在比赛时委托逆向的队友把符号表…

​【指针与数组的恩怨情仇】

指针和数组的关系 指针指的是指针变量&#xff0c;不是数组&#xff0c;指针变量的大小是4/8个字节&#xff0c;是专门来存放地址的。数组也不是指针&#xff0c;数组是一块连续的空间&#xff0c;存放一组相同类型的数据的。 没有关系&#xff0c;但是它们之间有比较相似的地方…

【Netty】一行简单的writeAndFlush都做了哪些事(十八)

文章目录 前言一、源码分析1.1 ctx.writeAndFlush 的逻辑1.2 writeAndFlush 源码1.3 ChannelOutBoundBuff 类1.4 addMessage 方法1.5 addFlush 方法1.6 AbstractNioByteChannel 类 总结 前言 回顾Netty系列文章&#xff1a; Netty 概述&#xff08;一&#xff09;Netty 架构设…

好用的Chrome浏览器插件推荐(不定期更新)

好用的Chrome浏览器插件推荐 1.1 CSDN-浏览器助手1.2 Google 翻译1.3 JSON Viewer1.4 ModHeader - Modify HTTP headers1.5 Octotree - GitHub code tree 1.1 CSDN-浏览器助手 CSDN-浏览器助手 是一款集成本地书签、历史记录与 CSDN搜索(so.csdn.net) 的搜索工具 推荐&#x…

自动驾驶车载MCU开发修炼秘籍

目录 车载MCU开发修炼秘籍1、恩智浦 S32K1XX系列2、英飞凌 AURIX TC3XX3、嵌入式实时操作系统-FreeRTOS4、车载实时操作系统-AUTOSAR 车载MCU开发修炼秘籍 1、恩智浦 S32K1XX系列 S32K14X学习笔记&#xff08;一&#xff09;–S32K汽车MCU资源总结 S32K14X学习笔记&#xff1a…

第二章 数据类型、运算符与表达式

如何打开项目 如何打开已经存在的解决方案&#xff1f; 找到要打开的解决方案目录&#xff0c;进去之后双击后缀为.sln的文件即可打开该解决方案。 或者从最近打开项目中打开&#xff1a; Online Judge使用 OJ简介 在线判题系统&#xff08;Online Judge&#xff0c;缩写OJ…