Skip to content

Commit

Permalink
feat: fashion report & infra update
Browse files Browse the repository at this point in the history
  • Loading branch information
Bluefissure committed Nov 13, 2023
1 parent 607f751 commit 2247435
Show file tree
Hide file tree
Showing 12 changed files with 577 additions and 432 deletions.
1 change: 1 addition & 0 deletions FFXIV/settings_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
'django.contrib.staticfiles',
'ffxivbot',
'channels',
'rest_framework',
]

MIDDLEWARE = [
Expand Down
11 changes: 9 additions & 2 deletions FFXIV/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,28 @@
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, re_path
from django.urls import path, re_path, include
from django.conf.urls.static import static
from django.conf import settings
from django.views.decorators.cache import cache_page

from ffxivbot.views import *
from ffxivbot.views.rest import FanshionReportViewSet
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

from rest_framework import routers

router = routers.DefaultRouter()
router.register(r'fashion_report', FanshionReportViewSet, basename='fashion_report')

urlpatterns = [
path('admin/', admin.site.urls),
path('', tata),
path('tata/', tata),
path('quest/', quest),
path('api/', api),
path('http/', qqpost),
path('wechat/message', wechatpost),
# path('wechat/message', wechatpost),
path('image/', image),
# path('hunt/', cache_page(60 * 2)()),
path('hunt/', hunt),
Expand All @@ -48,6 +54,7 @@
re_path(r'^register/', register),
re_path(r'^logout/', logout),
re_path(r'^auth/szj', szj_auth, name='szj_auth'),
path('rest/', include(router.urls)),
]
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
32 changes: 14 additions & 18 deletions ffxivbot/handlers/QQCommand_market.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from .QQEventHandler import QQEventHandler
from .QQUtils import *
from ffxivbot.models import *
from ffxivbot.models import QQUser
from difflib import SequenceMatcher
import logging
import json
Expand Down Expand Up @@ -118,6 +118,17 @@ def get_market_data(server_name, item_name, hq=False):
return msg


def handle_server_name_abbr(server_name):
map_dict = {
"鸟": "陆行鸟",
"猪": "莫古力",
"猫": "猫小胖",
"狗": "豆豆柴",
}
if server_name.upper() in map_dict:
server_name = map_dict[server_name.upper()]
return server_name

def handle_item_name_abbr(item_name):
if item_name.startswith("第二期重建用的") and item_name.endswith("(检)"):
item_name = item_name.replace("(", "(").replace(")", ")")
Expand Down Expand Up @@ -160,27 +171,12 @@ def handle_command(command_seg, user, group):
if time.time() < user.last_api_time + 15:
msg = "[CQ:at,qq={}] 技能冷却中,请勿频繁调用".format(user.user_id)
return msg
server = None
# server = None
if len(command_seg) != 3:
msg = "参数错误:\n/market item $name $server: 查询$server服务器的$name物品交易数据"
return msg
server_name = command_seg[-1]
if server_name in ("陆行鸟", "莫古力", "猫小胖", "豆豆柴"):
pass
elif server_name == "鸟":
server_name = "陆行鸟"
elif server_name == "猪":
server_name = "莫古力"
elif server_name == "猫":
server_name = "猫小胖"
elif server_name == "狗":
server_name = "豆豆柴"
else:
pass
# server = Server.objects.filter(name=server_name)
# if not server.exists():
# msg = '找不到服务器"{}"'.format(server_name)
# return msg
server_name = handle_server_name_abbr(server_name)
item_name = " ".join(command_seg[1:-1])
hq = "hq" in item_name or "HQ" in item_name
if hq:
Expand Down
236 changes: 118 additions & 118 deletions ffxivbot/handlers/QQCommand_treasure.py
Original file line number Diff line number Diff line change
@@ -1,127 +1,127 @@
from .QQEventHandler import QQEventHandler
from .QQUtils import *
from ffxivbot.models import *
import logging
import json
import random
import requests
import traceback
import time
import copy
import base64
import cv2
import numpy as np
import math
from bs4 import BeautifulSoup
# from .QQEventHandler import QQEventHandler
# from .QQUtils import *
# from ffxivbot.models import *
# import logging
# import json
# import random
# import requests
# import traceback
# import time
# import copy
# import base64
# import cv2
# import numpy as np
# import math
# from bs4 import BeautifulSoup


def get_image_from_CQ(CQ_text):
if "url=" in CQ_text:
tmp = CQ_text
tmp = tmp[tmp.find("url=") : -1]
tmp = tmp.replace("url=", "")
img_url = tmp.replace("]", "")
return img_url
return None
# def get_image_from_CQ(CQ_text):
# if "url=" in CQ_text:
# tmp = CQ_text
# tmp = tmp[tmp.find("url=") : -1]
# tmp = tmp.replace("url=", "")
# img_url = tmp.replace("]", "")
# return img_url
# return None

def img_diff(target, template):
try:
theight, twidth = template.shape[:2]
result = cv2.matchTemplate(target,template,cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
return min_val
except Exception as e:
traceback.print_exc()
return float("inf")
# def img_diff(target, template):
# try:
# theight, twidth = template.shape[:2]
# result = cv2.matchTemplate(target,template,cv2.TM_CCOEFF_NORMED)
# min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
# return min_val
# except Exception as e:
# traceback.print_exc()
# return float("inf")

def img_diff2(target, template):
def dhash(image):
resize_height, resized_width = 32, 33
resized_img = cv2.resize(image, (resized_width, resize_height))
grey_resized_img = cv2.cvtColor(resized_img, cv2.COLOR_RGB2GRAY)
hash_list = []
for row in range(resize_height):
for col in range(resized_width - 1):
if grey_resized_img[row, col] > grey_resized_img[row, col + 1]:
hash_list.append('1')
else:
hash_list.append('0')
return '' . join(hash_list)
def hamming_distance(dhash1, dhash2):
return bin(int(dhash1, base = 2) ^ int(dhash2, base = 2)).count('1')
return hamming_distance(dhash(target), dhash(template))
# def img_diff2(target, template):
# def dhash(image):
# resize_height, resized_width = 32, 33
# resized_img = cv2.resize(image, (resized_width, resize_height))
# grey_resized_img = cv2.cvtColor(resized_img, cv2.COLOR_RGB2GRAY)
# hash_list = []
# for row in range(resize_height):
# for col in range(resized_width - 1):
# if grey_resized_img[row, col] > grey_resized_img[row, col + 1]:
# hash_list.append('1')
# else:
# hash_list.append('0')
# return '' . join(hash_list)
# def hamming_distance(dhash1, dhash2):
# return bin(int(dhash1, base = 2) ^ int(dhash2, base = 2)).count('1')
# return hamming_distance(dhash(target), dhash(template))

def read_uri(uri):
encoded_data = uri.split(',')[1]
nparr = np.fromstring(base64.b64decode(encoded_data), np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
return img
# def read_uri(uri):
# encoded_data = uri.split(',')[1]
# nparr = np.fromstring(base64.b64decode(encoded_data), np.uint8)
# img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
# return img


def QQCommand_treasure(*args, **kwargs):
action_list = []
try:
# print("begin treasure ==============")
global_config = kwargs["global_config"]
receive = kwargs["receive"]
# def QQCommand_treasure(*args, **kwargs):
# action_list = []
# try:
# # print("begin treasure ==============")
# global_config = kwargs["global_config"]
# receive = kwargs["receive"]

# if int(receive["user_id"])!=306401806:
# msg = "功能暂时关闭中"
# reply_action = reply_message_action(receive, msg)
# action_list.append(reply_action)
# return action_list
# # if int(receive["user_id"])!=306401806:
# # msg = "功能暂时关闭中"
# # reply_action = reply_message_action(receive, msg)
# # action_list.append(reply_action)
# # return action_list

receive_msg = receive["message"].replace("/treasure", "", 1).strip()
msg_list = receive_msg.split(" ")
second_command = msg_list[0]
if second_command == "" or second_command == "help":
msg = "藏宝图查询:\n/treasure $image : 查询$image\nPS:截图请截到上下黑边,不要超过黑边."
else:
while "" in msg_list:
msg_list.remove("")
CQ_text = msg_list[0].strip()
img_url = get_image_from_CQ(CQ_text)
if not img_url:
msg = "未发现图片信息"
else:
res = requests.get(url=img_url, timeout=5)
template_uri = "data:" + res.headers['Content-Type'] + ";" +"base64," + base64.b64encode(res.content).decode("utf-8")
template = read_uri(template_uri)
min_diff = -1
min_treasuremap = None
max_diff = -1
max_treasuremap = None
for treasure_map in TreasureMap.objects.all():
target_uri = treasure_map.uri
target = read_uri(target_uri)
diff = img_diff2(target, template)
# rev_diff = img_diff(template, target)
# diff = min(rev_diff, diff)
print("diff with {}: {}".format(treasure_map, diff))
if min_diff == -1 or diff < min_diff:
min_diff = diff
min_treasuremap = treasure_map
if max_diff == -1 or diff > max_diff:
max_diff = diff
max_treasuremap = treasure_map
if math.isinf(min_diff):
msg = "图片匹配失败"
# elif (not min_treasuremap) or (max_diff > 0.25):
# msg = "未查询到有效藏宝图"
else:
territory = min_treasuremap.territory
pos_x, pos_y = json.loads(min_treasuremap.position)
map_url = "https://map.wakingsands.com/#f=mark&x={}&y={}&id={}".format(pos_x, pos_y, territory.mapid)
map_cq = "[CQ:image,file=base64://{}]\n".format(min_treasuremap.uri.replace("data:image/jpeg;base64,", ""))
msg = "地图:{} 编号:{} 坐标:({}, {})\n{}".format(territory, min_treasuremap.number, pos_x, pos_y, map_url)
msg = "[CQ:at,qq={}] ".format(receive["user_id"]) + msg
msg = msg.strip()
reply_action = reply_message_action(receive, msg)
action_list.append(reply_action)
return action_list
except Exception as e:
msg = "Error: {}".format(type(e))
action_list.append(reply_message_action(receive, msg))
logging.error(e)
traceback.print_exc()
return action_list
# receive_msg = receive["message"].replace("/treasure", "", 1).strip()
# msg_list = receive_msg.split(" ")
# second_command = msg_list[0]
# if second_command == "" or second_command == "help":
# msg = "藏宝图查询:\n/treasure $image : 查询$image\nPS:截图请截到上下黑边,不要超过黑边."
# else:
# while "" in msg_list:
# msg_list.remove("")
# CQ_text = msg_list[0].strip()
# img_url = get_image_from_CQ(CQ_text)
# if not img_url:
# msg = "未发现图片信息"
# else:
# res = requests.get(url=img_url, timeout=5)
# template_uri = "data:" + res.headers['Content-Type'] + ";" +"base64," + base64.b64encode(res.content).decode("utf-8")
# template = read_uri(template_uri)
# min_diff = -1
# min_treasuremap = None
# max_diff = -1
# max_treasuremap = None
# for treasure_map in TreasureMap.objects.all():
# target_uri = treasure_map.uri
# target = read_uri(target_uri)
# diff = img_diff2(target, template)
# # rev_diff = img_diff(template, target)
# # diff = min(rev_diff, diff)
# print("diff with {}: {}".format(treasure_map, diff))
# if min_diff == -1 or diff < min_diff:
# min_diff = diff
# min_treasuremap = treasure_map
# if max_diff == -1 or diff > max_diff:
# max_diff = diff
# max_treasuremap = treasure_map
# if math.isinf(min_diff):
# msg = "图片匹配失败"
# # elif (not min_treasuremap) or (max_diff > 0.25):
# # msg = "未查询到有效藏宝图"
# else:
# territory = min_treasuremap.territory
# pos_x, pos_y = json.loads(min_treasuremap.position)
# map_url = "https://map.wakingsands.com/#f=mark&x={}&y={}&id={}".format(pos_x, pos_y, territory.mapid)
# map_cq = "[CQ:image,file=base64://{}]\n".format(min_treasuremap.uri.replace("data:image/jpeg;base64,", ""))
# msg = "地图:{} 编号:{} 坐标:({}, {})\n{}".format(territory, min_treasuremap.number, pos_x, pos_y, map_url)
# msg = "[CQ:at,qq={}] ".format(receive["user_id"]) + msg
# msg = msg.strip()
# reply_action = reply_message_action(receive, msg)
# action_list.append(reply_action)
# return action_list
# except Exception as e:
# msg = "Error: {}".format(type(e))
# action_list.append(reply_message_action(receive, msg))
# logging.error(e)
# traceback.print_exc()
# return action_list
Loading

0 comments on commit 2247435

Please sign in to comment.