text
stringlengths
1
93.6k
从斗图啦表情包接口拉取图片
:param text: 搜索关键字
:return: 图片路径迭代器或者None
"""
url = 'https://www.doutula.com/search?keyword=' + text
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7'}
res = requests.get(url, headers=headers)
if res.status_code != 200:
return None
soup = BeautifulSoup(res.text, 'html.parser')
randomPics = soup.find_all('a', attrs={'class': 'col-xs-6 col-md-2'})
for pic in randomPics:
imgUrl = pic.find('img', attrs={'referrerpolicy': 'no-referrer'})['data-original']
try:
res = requests.get(imgUrl)
except:
return None
if res.status_code != 200:
continue
path = os.path.join('tmp', imgUrl[imgUrl.rfind('/') + 1:])
with open(path, 'wb') as f:
f.write(res.content)
yield path
def resizeImg(width: int, height: int) -> (int, int):
"""
重新设置图片大小
:param width: 图片宽度
:param height: 图片高度
:return: (width, height)
"""
default_width, default_height = 440, 360
if (width < default_width and height < default_height) or (width > default_width and height > default_height):
# 如果比例大于1.5,就不强制拉伸,按照宽度进行缩放
if width / height >= 1.5:
width, height = default_width, height * default_width / width
elif height / width > 1.5:
height, width = default_height, width * default_height / height
else:
# 小于1.5的强制拉伸
width, height = default_width, default_height
elif width > default_width and height <= default_height:
width, height = default_width, height * default_width / width
if height > default_height and width <= default_width:
height, width = default_height, width * default_height / height
return width, height
def convertToRGB(path: str) -> None:
"""
如果图片不是RGB模式,则转换成RGB模式,否则生成视频会出错
:param path: 图片路径
:return: None
"""
# convert to RGB
im = Image.open(path)
if im.mode != 'RGB':
im = im.convert('RGB')
# 获取exif是否正常,不正常则添加
try:
im.getexif()
im.save(path)
except:
exif_dict = {}
exif_dat = piexif.dump(exif_dict)
im.save(path, exif=exif_dat)
def baiduTranslate(text: str, zhcn2en: bool = True) -> str:
"""
将中文翻译成英文
:param text: 中文/英文
:param zhcn2en : 是否为中文转英文, 默认为是
:return: 英文/中文
"""
url = 'https://fanyi-api.baidu.com/api/trans/vip/translate'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
data = BAIDUAPPID + text + url + BAIDUAPPKEY
md5 = hashlib.md5()
md5.update(data.encode('utf-8'))
if zhcn2en:
data = {'appid': BAIDUAPPID, 'q': text, 'from': 'zh', 'to': 'en', 'salt': url, 'sign': md5.hexdigest()}
else:
data = {'appid': BAIDUAPPID, 'q': text, 'from': 'en', 'to': 'zh', 'salt': url, 'sign': md5.hexdigest()}
res = requests.post(url, data=data, headers=headers)
if res.status_code != 200:
return ''
res = json.loads(res.text)
if 'trans_result' not in res:
return ''
result = ''
for trans in res['trans_result']:
result += trans['dst'] + '。'
return result