<jupyter_start><jupyter_text>![](https://ai-studio-static-online.cdn.bcebos.com/72133691dfbc45ddafc30acc76d5ad931c281b2b637c40bdba4dd5efa4e479d1) Wander[001] - 未来流浪者——基于WeChaty, PaddleHub与彩云小梦的科幻机器人一个身处未来，正在努力穿越地球的旅行者。 可以跟人类发送当前定位、照片和游记。发送“我想去：”+地点，即可获得当地未来时期的照片，以及Wander的游记。希望做成一个互联网艺术项目，成为参与者聊天列表里一位特殊的旅行者，给参与者带去一些期待和惊喜。![](https://ai-studio-static-online.cdn.bcebos.com/bf58434f513f4e3a8ae36c121bba1423a1f005193a994cb388d113cac27f4df5)![](https://ai-studio-static-online.cdn.bcebos.com/8961050f9b7a46a396d56192f7592c55d1607c3a1ebf4510abf50592842a8984)![](https://ai-studio-static-online.cdn.bcebos.com/0893f4ced8874e2180d16d3802fff0149ce1b3ab8896480da5f9520d6e24d47b)![](https://ai-studio-static-online.cdn.bcebos.com/57e73493b3074255b4c25112d7be8fec8c35a6cd948c4a7c8e4a45f899f89d80)   实现流程获取地理信息，如 [北京大学东门] =》调用百度地图api地图检索功能，根据地点搜索获取gps坐标 [http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-placeapi](http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-placeapi)    =》调用百度地图api全景静态图功能，获取该坐标对应的街景图 [http://lbsyun.baidu.com/index.php?title=viewstatic](http://lbsyun.baidu.com/index.php?title=viewstatic)        =》调用PaddleHub风格迁移模型，迁移成未来风格 [https://aistudio.baidu.com/aistudio/projectdetail/439779?channelType=0&channel=0](https://aistudio.baidu.com/aistudio/projectdetail/439779?channelType=0&channel=0)        =》调用彩云小梦api，生成游记[https://open.caiyunapp.com/%E5%BD%A9%E4%BA%91%E5%B0%8F%E6%A2%A6API](https://open.caiyunapp.com/%E5%BD%A9%E4%BA%91%E5%B0%8F%E6%A2%A6API)=》通过WeChaty返回消息给用户[https://wechaty.js.org/](https://wechaty.js.org/)                       准备工作服务器搭建，以及WeChaty Token获取的部分请参考：[https://aistudio.baidu.com/aistudio/projectdetail/1836012](https://aistudio.baidu.com/aistudio/projectdetail/1836012)百度地图的api Token(ak)可通过在官网控制台创建应用获得[http://lbsyun.baidu.com/index.php?title=%E9%A6%96%E9%A1%B5](http://lbsyun.baidu.com/index.php?title=%E9%A6%96%E9%A1%B5)彩云小梦的api Token需要通过邮件申请[https://open.caiyunapp.com/%E5%BD%A9%E4%BA%91%E5%B0%8F%E6%A2%A6API](https://open.caiyunapp.com/%E5%BD%A9%E4%BA%91%E5%B0%8F%E6%A2%A6API)  ![](https://ai-studio-static-online.cdn.bcebos.com/afb78d903d74484eb3ad95653d792f652ba75e0ad22c4111b9630994821b03ae)    代码实现<jupyter_code>#导入相关库
import os
import asyncio
import requests,json,time
os.environ['WECHATY_PUPPET_SERVICE_TOKEN'] = '你的wechaty token'
os.environ['WECHATY_PUPPET_HOSTIE_TOKEN'] = '你的wechaty token'
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
text='wait'
import urllib.request  #打开网页模块
import urllib.parse    #转码模块
from bs4 import BeautifulSoup
from urllib.parse import quote
from PIL import Image
import json

import paddlehub as hub
import cv2
import matplotlib.image as mpimg

stylepro_artistic = hub.Module(name="stylepro_artistic")
_lng=''
_lat=''
from wechaty import (
    Contact,
    FileBox,
    Message,
    Wechaty,
    ScanStatus,
)
#在接收到消息时执行
async def on_message(msg: Message):

    talker = msg.talker()

    if "我想去：" in msg.text():
        location=msg.text().replace('我想去：', '')
        await talker.say('正在前往：'+location)
        print('准备定位')
        print(location)
        path=findLocation(location)
        print('已完成生成')
        print(path)

        if path is None:
            await talker.say('获取失败，请重试')
        else:
            file_box_4 = FileBox.from_file(path)
            await talker.say('降落成功。'  + '\n'+ '经度：'+_lng+ '\n'+'纬度：'+_lat)
            await talker.say(file_box_4)
            #续写
            title="科幻小说：星舰地球-未来宇宙日志01"
            content='这里是3050年的'+location+'。我的飞行器缓缓降落。'
            mid='60211134902769d45689bf75'
            res_from_caiyunai=create_from_caiyunai(title,content,mid)
            if res_from_caiyunai:
                result=res_from_caiyunai[0]
                data=json.dumps(result)
                final = json.loads(data)['content']
                await msg.say(content+str(final))

#测试功能
    if msg.text() == 'ding':
        await msg.say('这是自动回复: dong dong dong')
#测试功能
    if msg.text() == 'hi' or msg.text() == '你好':
        await msg.say( '你好，我是在未来的地球上流浪的机器人。')

#测试功能。发动续写
    if "续写：" in msg.text():
        #调用彩云
        title="科幻小说：未来宇宙流浪日志01"
        content=msg.text().replace('续写：', '')
        mid='60211134902769d45689bf75'
        res_from_caiyunai=create_from_caiyunai(title,content,mid)
        if res_from_caiyunai:
            result=res_from_caiyunai[0]
            data=json.dumps(result)
            final = json.loads(data)['content']
            await msg.say(content+str(final))
        # 构建一个FileBox
        file_box_1 = FileBox.from_url(url=url, name='xx.jpg')

        await msg.say(file_box_1)

async def on_scan(
        qrcode: str,
        status: ScanStatus,
        _data,
):
    print('Status: ' + str(status))
    print('View QR Code Online: https://wechaty.js.org/qrcode/' + qrcode)


async def on_login(user: Contact):
    print(user)


async def main():
    # 确保我们在环境变量中设置了WECHATY_PUPPET_SERVICE_TOKEN
    if 'WECHATY_PUPPET_SERVICE_TOKEN' not in os.environ:
        print('''
            Error: WECHATY_PUPPET_SERVICE_TOKEN is not found in the environment variables
            You need a TOKEN to run the Python Wechaty. Please goto our README for details
            https://github.com/wechaty/python-wechaty-getting-started/#wechaty_puppet_service_token
        ''')

    bot = Wechaty()

    bot.on('scan',      on_scan)
    bot.on('login',     on_login)
    bot.on('message',   on_message)

    await bot.start()

    print('[Python Wechaty] Ding Dong Bot started.')

# 输入地名，最终返回生成图片的地址
def findLocation(address):

	ak = "你的百度地图ak"
	url="http://api.map.baidu.com/geocoding/v3/?address="+quote(address)+"&output=json&ak="+ak
	print(url)
	global _lng
	global _lat

	request = urllib.request.Request(url)
	with urllib.request.urlopen(request) as f:
		html = f.read()#.decode('utf-8')

	soup = BeautifulSoup(html, 'html.parser')
	data = json.loads(str(soup))

	if "无相关结果" in str(data):
		return str(data)
	else:
		lng   = data["result"]["location"]["lng"]
		lat   = data["result"]["location"]["lat"]
		level = data["result"]["level"]
		#如果获取坐标，保存图片并加水印
        #返回图片地址
		final=getPicture(str(lng),str(lat))
		_lng=str(lng)
		_lat=str(lat)
		print('经度'+_lng+'纬度'+_lat)
		return final
#根据坐标，调取街景图
def getPicture(longitude,latitude):
	url = "https://api.map.baidu.com/panorama/v2?&width=1024&height=512&location="+longitude+","+latitude+"&ak=pn6hX9AEgMoSX2IXOH4iNjkN2MKoOuHV&fov=180"
	print(url)

	request = urllib.request.Request(url)
	with urllib.request.urlopen(request) as f:
		html = f.read().decode("ISO-8859-1")

	soup = BeautifulSoup(html, 'html.parser')

	if "message" in str(soup):
		print("返回错误信息：如下：",soup)
	else:
		save_name = "./pictures/" + longitude + "_" + latitude + ".jpg"

		rep = urllib.request.urlopen(url)
		# 将图片存入本地，创建一个save_name的文件，wb为写入
		f = open(save_name, 'wb')
		# 写入图片
		f.write(rep.read())
		f.close()
		print("成功获取图片！")

		#获取的图片地址
		save_path = "./pictures/" + longitude + "_" + latitude + ".jpg"
		#迁移后的名字
		save_new_name = longitude + "_" + latitude + "new.jpg"
		#贴完水印的地址
		save_final_name ="./transfer_result/"+ longitude + "_" + latitude + "final.jpg"
        #风格迁移
		motherPath=img_transform(save_path,save_new_name)
		print("成功迁移风格")

		#加水印
		Picture_Synthesis(mother_img=motherPath,
						  son_img="realLogo.png",
						  save_img=save_final_name,
						  coordinate=None  # 如果为None表示直接将子图在母图中居中也可以直接赋值坐标
						  )
		print("成功添加自定义水印！")
        #返回图片地址
		return save_final_name
#风格迁移
def img_transform(img_path, img_name):

    #img_path: 图片的路径
    #img_name: 图片的文件名
    # 图片转换后存放的路径
    img_new_path = './transfer_result/' + img_name

    # 模型预测
    result = stylepro_artistic.style_transfer(images=[{
        'content': cv2.imread(img_path),
        'styles': [cv2.imread("styles/style7.jpg")]}],
        alpha = 1.0,
        visualization = True)

    # 将图片保存到指定路径
    cv2.imwrite(img_new_path, result[0]['data'])

    # 返回新图片的路径
    return img_new_path

#给图片打水印
def Picture_Synthesis(mother_img,
                      son_img,
                      save_img,
                      coordinate=None):
    """
    :param mother_img: 母图
    :param son_img: 子图
    :param save_img: 保存图片名
    :param coordinate: 子图在母图的坐标
    :return:
    """
    #将图片赋值,方便后面的代码调用
    M_Img = Image.open(mother_img)
    S_Img = Image.open(son_img)

    # 获取图片的尺寸
    M_Img_w, M_Img_h = M_Img.size  # 获取被放图片的大小（母图）
    S_Img_w, S_Img_h = S_Img.size  # 获取小图的大小（子图）

    # # 重新设置子图的尺寸
    #icon = S_Img.resize((321, 60), Image.ANTIALIAS)
    icon = S_Img
    w = 23
    h = int((M_Img_h) - 23-60)

    try:
        if coordinate==None or coordinate=="":
            coordinate=(w, h)
            # 粘贴子图到母图的指定坐标（当前居中）
            M_Img.paste(icon, coordinate, mask=None)
        else:
            print("已经指定坐标")
            # 粘贴子图到母图的指定坐标（当前居中）
            M_Img.paste(icon, coordinate, mask=None)
    except:
        print("坐标指定出错 ")
    # 保存图片
    M_Img.save(save_img)

#彩云续写
    #选择模型
    #小梦0号：60094a2a9661080dc490f75a
    #小梦1号：601ac4c9bd931db756e22da6
    #纯爱：601f92f60c9aaf5f28a6f908
    #言情：601f936f0c9aaf5f28a6f90a
    #玄幻：60211134902769d45689bf75

def create_from_caiyunai(title, content,mid="60094a2a9661080dc490f75a"):
    global nid
    url = "http://if.caiyunai.com/v1/dream/"
    token = "<PASSWORD>"

    #创建文章
    payload = {
                "content" : content,
                "title" : title,
               }
    response = requests.request("POST", url + token + "/novel_save", data=json.dumps(payload))
    nid = json.loads(response.text)['data']['nid']

    #发起续写
    payload = {
            "content" : content,
            "title" : title,
            "mid": mid,
            "nid": nid
            }
    response = requests.request("POST", url + token + "/novel_ai", data=json.dumps(payload))

    try:
        xid=json.loads(response.text)['data']['xid']
    except:
        print('续写失败:',response.text)
        return;

    #等待结果
    while True:
      time.sleep(1)
      #获取结果
      payload = {
              "xid": xid,
              "nid": nid
              }
      response = requests.request("POST", url + token + "/novel_dream_loop", data=json.dumps(payload))
      if json.loads(response.text)['data']['count']==0:
        res = json.loads(response.text)['data']['rows']
        break

    return res
asyncio.run(main())<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13987671882408725, 'fraction_numerical': 0.05158843053579896, 'mean_word_length': 2.981124952812382, 'pattern_counts': {'":': 5, '<': 6, '<?xml version=': 0, '>': 6, 'https://': 19, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '645956', 'license': 'Apache-2.0', 'n_tokens_mistral': 5094, 'n_tokens_neox': 4893, 'n_words': 523, 'path': 'wander.ipynb', 'repo_name': 'LaudateCorpus1/WanderBot_public', 'size': '10546'}