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

news2024/10/2 12:17:14

诸神缄默不语-个人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
  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.coloradmin.cn/o/584839.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

终极AI工具包【第一章 如何学习ChatGPT(基础知识)】

第1章&#xff1a;如何学习ChatGPT&#xff08;基础知识&#xff09; 1、什么是ChatGPT ChatGPT是OpenAI开发的一种人工智能&#xff08;AI&#xff09;语言模型。它是在一个称为GPT&#xff08;生成预训练变压器&#xff09;的架构下构建的&#xff0c;目的是理解和生成人类语…

商城配置-shorp

商城配置 说明 商城配置主要分为三块&#xff0c;基础配置&#xff0c;平台配置&#xff0c;支付配置,所有配置请都检查配置一下&#xff0c;文档中只对部分配置进行说明 基础配置 基础配置说明 基础配置包括&#xff0c;商城信息&#xff0c;会员配置&#xff0c;分享配置&am…

考研算法复试刷题19天:Prim算法求最小生成树 【prim,最小生成树】

最小生成树 参考博客&#xff1a;图解&#xff1a;什么是最小生成树&#xff1f; - 知乎 (zhihu.com) 总结下来的过程就是&#xff0c;一张图&#xff0c;我们将他化为树的形式&#xff0c;也就是生成树。那么最小生成树有是啥呢&#xff1f;所谓一个 带权图 的最小生成树&a…

图片类主题TOB主题1.0_WordPress主题

WordPress tob主题是一款基于WordPress程序的专业图片类主题&#xff0c;在图片展示上做了很多工作&#xff0c;扁平化设计、自适应响应式布局、多设备支持、强大的主题功能配置&#xff0c;希望tob主题可以开启图片站新时代。 tob主题1.0版本更新内容&#xff1a; 新增首页置…

ProtoBuf的安装

ProtoBuf的安装 &#x1f50e;下载ProtoBuf编译器&#x1f50e;配置环境变量&#x1f50e;验证&#x1f50e;结尾 文章中安装的 ProtoBuf 版本为 v21.11 如果需要其他版本, 可根据自身需要选择相对应的版本进行下载 (步骤都是类似的) &#x1f50e;下载ProtoBuf编译器 点击链接…

websocket在分布式场景的应用方案

websocket简介 WebSocket 是一种在单个 TCP 连接上进行全双工通信的协议。它可以在客户端和服务器之间建立持久连接&#xff0c;使得服务器可以主动向客户端推送数据&#xff0c;而不需要客户端不断地向服务器发送请求。 WebSocket 协议的优点包括&#xff1a; 实时性&#x…

matlab将图像转成单列(可还原)

在MATLAB中&#xff0c;通过使用 image(:) 将二维图像转换为一列时&#xff0c;元素的顺序是按列主序&#xff08;column-major order&#xff09;进行排列。 具体而言&#xff0c;对于一个 M 行 N 列的二维图像&#xff0c;image(:) 将按照列的顺序将图像的元素存储到一列向量…

凸缺陷 convexityDefects

获取凸包&#xff0c;可以参考我的这篇文章&#xff1a; 凸包&#xff08;Convex Hull&#xff09;代码实现案例 获取了凸包之后&#xff0c;可以干什么呢&#xff1f; 凸缺陷凸包与轮廓之间的部分称为凸缺陷。凸缺陷可用来处理手势识别等问题。 通常情况下&#xff0c;使用如…

单位公派|消化内科医生赴美国藤校耶鲁大学访学

N医生依据单位公派要求及本人专业特点&#xff0c;希望申请到美国排名靠前的名校或医疗机构从事一年的访问交流。我们申请到了数个世界知名高校&#xff0c;最终其选择了专业高度匹配的常春藤高校-耶鲁大学。 N医生背景&#xff1a; 申请类型&#xff1a;单位公派 工作背景&a…

RFID软件在现代智能制造中的应用

随着机器人、传感器等新兴技术的普及&#xff0c;智能制造正在成为制造业发展的新趋势。而RFID软件作为智能制造技术中的重要应用&#xff0c;具有广泛的应用前景和优势。 一、RFID软件的应用原理 RFID即无线射频识别&#xff0c;它是一种利用无线电波自动识别物体的技术。RF…

上四休三听起来很爽?现实可能没有那么美好

就在各位996人还在羡慕朝九晚五周末双休时&#xff0c;有些企业则走得更远&#xff0c;上四休三都出来了&#xff01;据媒体报道&#xff0c;近期&#xff0c;浙江温州的一家创意公司火了&#xff0c;该公司的招聘信息表示&#xff0c;在保证薪资和社保的前提下&#xff0c;员工…

交叉导轨在光学测试仪和光学工作台中的应用

交叉导轨主要是安装在高精密加工的工作台与基座之间的一种装置&#xff0c;它的安装需要主要是适合了高精密、小型和一些高性能的平台工作的需要。 交叉导轨在应用的过程中也是起到了很多方面的作用的。像精密检测仪器&#xff0c;自动化设备&#xff0c;还有一些检查设备中等等…

基于Springboot + Vue3的云盘系统

目录 一. &#x1f981; 前言二. &#x1f981; 主要技术栈三. &#x1f981; 架构搭建1. 项目搭建效果2. 各部分作用 四. &#x1f981; 主要功能1.功能图2. 主要功能2.1 分片上传文件2.2 存储分享记录 五. &#x1f981; 效果显示 一. &#x1f981; 前言 源码获取地址&#…

Python常用遥感模块Rasterio与Rioxarray的安装与使用

1. Rasterio与Rioxarray安装 Rasterio 是一个很多模块是基于 GDAL 的 Python 包&#xff0c;可用于处理地理空间栅格数据&#xff0c;例如 GeoTIFF 文件。为此&#xff0c;可以使用许多模块和函数&#xff0c;例如&#xff0c;处理来自卫星的原始数据、读取栅格数据、检索地理…

什么是API接口,API接口类型有哪些?

随着互联网技术的不断发展&#xff0c;全球网络数据呈现爆炸式增长&#xff0c;如何从这些数据中挖掘出有价值的信息变得愈发重要。API接口作为一种重要的数据获取方式&#xff0c;逐渐引起了人们的关注。 API&#xff08;Application Programming Interface&#xff09;是软件…

pip安装软件包报错: error subprocess-exited-with-error问题记录

问题修复 执行pip install dlib 在执行pip3 install virtualenvwrapper也会报同样的错误 问题修复 我们需要执行如下命令&#xff1a; pip install --upgrade setuptoolspip install --upgrade setuptools 命令用于升级 setuptools 库的版本。setuptools 是 Python 的一个开…

python+selenium做ui自动化测试用法必会

一、前言 大家都知道&#xff0c;基于Web端的测试的基础框架是需要Selenium做主要支撑的&#xff0c;这里边给大家介绍下Web测试核心之基于 Python 的 Selenium Selenium 是用于测试 Web 应用程序用户界面 (UI) 的常用框架。它是一款用于运行端到端功能测试的超强工具。您可以…

已签名驱动程序安装后提示“Windows无法验证此设备所需驱动程序数字签名”的原因和解决方法

在Windows 64位系统上&#xff0c;正常开启数字签名认证时&#xff0c;驱动程序软件需要经过微软数字签名的才允许被使用。否则在设备管理器下&#xff0c;安装完硬件驱动后设备上会有“黄色感叹号”标识&#xff0c;右键该设备属性提示&#xff1a;“Windows 无法验证此设备所…

项目管理的49个过程的数据流向

请点击↑关注、收藏&#xff0c;本博客免费为你获取精彩知识分享&#xff01;有惊喜哟&#xff01;&#xff01; 过程组主要数据流 启动过程组 规划过程组 执行过程组 监控过程组 收尾过程组 4、项目整合管理 4.1制定项目章程 4.2制定项目管理计划 4.3指导与管理项目工作 4.4…

【28】核心易中期刊推荐——医学影像识别及应用

🚀🚀🚀NEW!!!核心易中期刊推荐栏目来啦 ~ 📚🍀 核心期刊在国内的应用范围非常广,核心期刊发表论文是国内很多作者晋升的硬性要求,并且在国内属于顶尖论文发表,具有很高的学术价值。在中文核心目录体系中,权威代表有CSSCI、CSCD和北大核心。其中,中文期刊的数…