Skip to content

Commit

Permalink
TraceMoe番剧中文名称获取
Browse files Browse the repository at this point in the history
  • Loading branch information
kitUIN committed Jul 13, 2021
1 parent 799a872 commit 8fd8947
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 16 deletions.
64 changes: 55 additions & 9 deletions PicImageSearch/tracemoe.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import requests
from loguru import logger
from pathlib import Path
from urllib import parse


class TraceMoeAnilist:
Expand All @@ -11,6 +12,9 @@ def __init__(self, data):
self.synonyms: list = data['synonyms'] # 备用英文标题
self.isAdult: bool = data['isAdult'] # 是否R18

def setChinese(self, data):
self.title = data

def __repr__(self):
return f'(<id={repr(self.id)}, idMal={repr(self.idMal)}, title={repr(self.title)},' \
f' synonyms={repr(self.synonyms)}, isAdult={repr(self.isAdult)})> '
Expand All @@ -21,6 +25,7 @@ def __init__(self, data, mute=False, size=None):
self.origin: dict = data
if type(data['anilist']) == dict:
self.anilist = TraceMoeAnilist(data['anilist'])
self.anilist.setChinese(self.animeTitle(data['anilist']['id']))
else:
self.anilist: int = data['anilist'] # 匹配的Anilist ID见https://anilist.co/
self.filename: str = data['filename'] # 找到匹配项的文件名
Expand Down Expand Up @@ -102,6 +107,32 @@ def download_video(self, filename='video.mp4', path: Path = Path.cwd()) -> Path:

return endpoint

def animeTitle(self, anilistID):
# Here we define our query as a multi-line string
query = '''
query ($id: Int) { # Define which variables will be used in the query (id)
Media (id: $id, type: ANIME) { # Insert our variables into the query arguments (id) (type: ANIME is hard-coded in the query)
id
title {
romaji
english
native
}
}
}
'''

# Define our query variables and values that will be used in the query request
variables = {
'id': anilistID
}

url = 'https://trace.moe/anilist/'

# Make the HTTP Api request
response = requests.post(url, json={'query': query, 'variables': variables})
return response.json()['data']['Media']['title']

def __repr__(self):
return f'<NormTraceMoe(filename={repr(self.filename)}, similarity={self.similarity:.2f})>'

Expand Down Expand Up @@ -199,6 +230,27 @@ def me(self, key=None): # 获取自己的信息
except Exception as e:
logger.info(e)

def _firstIf(self, param):
if param != "":
param += "&"
return param

def setParams(self, url, anilistID, anilistInfo, cutBorders):
params = ""
if anilistInfo:
params = self._firstIf(params)
params += "anilistInfo"
if cutBorders:
params = self._firstIf(params)
params += "cutBorders"
if anilistID:
params = self._firstIf(params)
params += f"anilistID={str(anilistID)}"
if url:
params = self._firstIf(params)
params += f"url={parse.quote_plus(url)}"
return params

def search(self, url, key=None, anilistID=None, anilistInfo=True, cutBorders=True):
"""识别图片
Expand All @@ -210,17 +262,10 @@ def search(self, url, key=None, anilistID=None, anilistInfo=True, cutBorders=Tru
"""
try:
headers = None
params = dict()
if anilistID:
params['anilistID'] = anilistID
if cutBorders:
params['cutBorders'] = None
if anilistInfo:
params['anilistInfo'] = None
if headers:
headers = {"x-trace-key": key}
if url[:4] == 'http': # 网络url
params['url'] = url
params = self.setParams(url, anilistID, anilistInfo, cutBorders)
res = requests.get(self.TraceMoeURL, headers=headers, params=params, verify=False,
**self.requests_kwargs)
if res.status_code == 200:
Expand All @@ -229,7 +274,8 @@ def search(self, url, key=None, anilistID=None, anilistInfo=True, cutBorders=Tru
else:
logger.error(self._errors(res.status_code))
else: # 是否是本地文件
res = requests.post(self.TraceMoeURL, headers=headers,
params = self.setParams(None, anilistID, anilistInfo, cutBorders)
res = requests.post(self.TraceMoeURL, headers=headers, params=params,
files={"image": open(url, "rb")}, **self.requests_kwargs)
if res.status_code == 200:
data = res.json()
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

setuptools.setup(
name="PicImageSearch",
version='2.0.1',
version='2.0.3',
author="kitUIN",
author_email="[email protected]",
description="PicImageSearch APIs for Python 3.x 适用于 Python 3 以图搜源整合API",
Expand Down
10 changes: 4 additions & 6 deletions test/test1.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from loguru import logger
from PicImageSearch.tracemoe import TraceMoe

tracemoe = TraceMoe(mute=False)
# res = tracemoe.search('https://trace.moe/img/tinted-good.jpg')# 搜索网络图片
res = tracemoe.search(r'C:/Users/kulujun/Pictures/1.png') # 搜索本地图片
tracemoe = TraceMoe(mute=False,size=None)
res = tracemoe.search('https://trace.moe/img/tinted-good.jpg')# 搜索网络图片
# res = tracemoe.search(r'C:/Users/kulujun/Pictures/1.png') # 搜索本地图片
logger.info(res.origin)
logger.info(res.raw)
logger.info(res.raw[0])
Expand All @@ -16,9 +16,7 @@
logger.info(res.raw[0].similarity)
logger.info(res.raw[0].video)
logger.info(res.raw[0].image)
logger.info(res.raw[0].download_image())
logger.info(res.raw[0].download_video())
logger.info(tracemoe.me())

# ---------------过时版本-----------------------
# logger.info(res.origin)
# logger.info(res.raw) # [<NormTraceMoe(title='心連·情結', similarity=0.97)>, <NormTraceMoe(title='涼宮春日的憂鬱', similarity=0.82)>, <NormTraceMoe(title='涼宮春日的憂鬱 2009', similarity=0.82)>, <NormTraceMoe(title='鑽石王牌 第二季', similarity=0.82)>, <NormTraceMoe(title='Soul Link', similarity=0.81)>, <NormTraceMoe(title='神之見習者秘密的心靈蛋', similarity=0.81)>, <NormTraceMoe(title='銀狐', similarity=0.81)>, <NormTraceMoe(title='驅魔少年', similarity=0.81)>]
Expand Down

0 comments on commit 8fd8947

Please sign in to comment.