First commit
Former-commit-id: 424079609133edcc501ae185509836ee1181a02c
This commit is contained in:
11
change_font/.gitignore
vendored
Normal file
11
change_font/.gitignore
vendored
Normal file
@ -0,0 +1,11 @@
|
||||
ipt
|
||||
opt
|
||||
out
|
||||
*.png
|
||||
*.jpg
|
||||
*.json
|
||||
*.ttf
|
||||
temp_*
|
||||
*.exe
|
||||
*.ini
|
||||
*.conf
|
52
change_font/application_json.py
Normal file
52
change_font/application_json.py
Normal file
@ -0,0 +1,52 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
author: yu.hailong
|
||||
email: yuhailong@100tal.com
|
||||
datetime: 2020/4/23 2:34 下午
|
||||
description:
|
||||
urlencoded methods
|
||||
"""
|
||||
|
||||
import time
|
||||
from util.send_sign_http import send_request
|
||||
from util.http import application_json
|
||||
|
||||
|
||||
class ApplicationJsonMethods:
|
||||
def __init__(self, ACCESS_KEY_ID:str, ACCESS_KEY_SECRET:str) -> None:
|
||||
'''
|
||||
@brief 以json形式发送数据
|
||||
@param ACCESS_KEY_ID: 注册应用时的ACCESS_KEY_ID
|
||||
@param ACCESS_KEY_SECRET:注册应用时的ACCESS_KEY_SECRET
|
||||
'''
|
||||
self.header = application_json
|
||||
self.ACCESS_KEY_ID = ACCESS_KEY_ID
|
||||
self.ACCESS_KEY_SECRET = ACCESS_KEY_SECRET
|
||||
|
||||
def response(self, method:str, HTTP_URL:str, body_params=None,payload={}):
|
||||
'''
|
||||
@parms:
|
||||
method: GET、POST、PUT、PATCH、DELETE
|
||||
'''
|
||||
assert body_params is not None
|
||||
|
||||
# 获取当前时间(东8区)
|
||||
timestamp = time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime())
|
||||
|
||||
result = send_request(self.ACCESS_KEY_ID, self.ACCESS_KEY_SECRET, timestamp, HTTP_URL, payload, body_params, method,
|
||||
self.header)
|
||||
return result
|
||||
|
||||
def get(self, *args, **kwargs):
|
||||
method="GET"
|
||||
return self.response(method,*args,**kwargs)
|
||||
|
||||
def post(self, *args, **kwargs):
|
||||
method="POST"
|
||||
return self.response(method,*args,**kwargs)
|
||||
|
||||
def delete(self, *args, **kwargs):
|
||||
method = "DELETE"
|
||||
return self.response(method,*args,**kwargs)
|
||||
|
||||
|
24
change_font/bg.py
Normal file
24
change_font/bg.py
Normal file
@ -0,0 +1,24 @@
|
||||
from req import Req
|
||||
from json import dump
|
||||
from time import sleep
|
||||
from base64 import b64decode
|
||||
import pickle
|
||||
|
||||
# cnter='7'
|
||||
url="https://openai.100tal.com/aiimage/comeducation"
|
||||
# file=f"opt/{str(cnter)}new.jpg"
|
||||
file="opt/DINGTALK_IM_1659828452.JPGnew.JPG"
|
||||
req=Req(warn=False)
|
||||
if not req.ready:
|
||||
id=input("ID: ")
|
||||
sec=input("Secret: ")
|
||||
req.set(id,sec)
|
||||
bgpic=req("http://openai.100tal.com/aiimage/handwriting-erase",file)
|
||||
|
||||
if bgpic["code"]!=20000:
|
||||
print(bgpic)
|
||||
with open("bg.json","w",encoding="utf-8") as f:
|
||||
dump(bgpic,f)
|
||||
exit(-1)
|
||||
with open("bg.png","wb") as f:
|
||||
f.write(b64decode(bgpic["image_base64"]))
|
71
change_font/main.py
Normal file
71
change_font/main.py
Normal file
@ -0,0 +1,71 @@
|
||||
from req import Req
|
||||
import cv2
|
||||
import numpy as np
|
||||
# from matplotlib import pyplot as plt
|
||||
from json import dump
|
||||
from PIL import ImageFont,Image,ImageDraw
|
||||
from random import randint
|
||||
from time import sleep
|
||||
import pickle
|
||||
|
||||
# cnter='7'
|
||||
url="https://openai.100tal.com/aiimage/comeducation"
|
||||
# file=f"opt/{str(cnter)}new.jpg"
|
||||
file="opt/DINGTALK_IM_1659828452.JPGnew.JPG"
|
||||
req=Req(warn=False)
|
||||
if not req.ready:
|
||||
id=input("ID: ")
|
||||
sec=input("Secret: ")
|
||||
req.set(id,sec)
|
||||
data:dict=req(url,file,function=2,subject="liberat")
|
||||
if "data" not in data.keys():
|
||||
print(data)
|
||||
exit(-1)
|
||||
with open("data.conf","wb") as f:
|
||||
pickle.dump(data,f)
|
||||
|
||||
|
||||
|
||||
# with open("data.conf","rb") as f:
|
||||
# data=pickle.load(f)
|
||||
|
||||
data=data["data"]
|
||||
|
||||
img=cv2.imread("bg.png")
|
||||
rows,cols,_=img.shape
|
||||
fontbase=ImageFont.truetype("font.ttf",100)
|
||||
arr=[]
|
||||
cnt=-1
|
||||
|
||||
for string in data["result"]:
|
||||
length=len(string["texts"])
|
||||
size=0
|
||||
temp=cnt+1
|
||||
for char in string["char_info"]:
|
||||
x0,y0=char["pos"][0].values()
|
||||
x1,y1=char["pos"][2].values()
|
||||
size+=(max(x1-x0,y1-y0)+min(x1-x0,y1-y0))/2
|
||||
arr.append([x0,x1,y0,y1,char["char"],None])
|
||||
# img[(y0-2):(y1+2),(x0-2):(x1+2)]=(255,255,255)
|
||||
cnt+=1
|
||||
arr[temp][5]=int(size//(length-4))
|
||||
|
||||
# cv2.imwrite("background.png",img)
|
||||
img_pil=Image.fromarray(img)
|
||||
draw=ImageDraw.Draw(img_pil)
|
||||
|
||||
|
||||
size=1000
|
||||
for x0,x1,y0,y1,char,_size in arr:
|
||||
print(_size)
|
||||
size=_size if _size is not None else size
|
||||
font=fontbase.font_variant(size=size)
|
||||
draw.text((x0,y0),char,(0,0,0),font)
|
||||
img_2=np.array(img_pil)
|
||||
# cv2.imwrite(f"out/{str(cnter)}.png",img_2)
|
||||
cv2.imwrite(f"out.png",img_2)
|
||||
|
||||
# a,b=plt.subplots(1,2,True,True)
|
||||
# b[0].imshow(img)
|
||||
# b[1].imshow(img_2)
|
||||
# plt.show()
|
48
change_font/req.py
Normal file
48
change_font/req.py
Normal file
@ -0,0 +1,48 @@
|
||||
from application_json import ApplicationJsonMethods
|
||||
from base64 import b64encode
|
||||
from json import dump, load,loads
|
||||
from os.path import exists
|
||||
|
||||
|
||||
class Req(ApplicationJsonMethods):
|
||||
def __init__(self, key_id: str = None, key_sec: str = None,warn=True):
|
||||
if key_id is None or key_sec is None:
|
||||
self.ready = self.from_file()
|
||||
else:
|
||||
self.key_id = key_id
|
||||
self.key_sec = key_sec
|
||||
self.ready = True
|
||||
if self.ready:
|
||||
super().__init__(self.key_id, self.key_sec)
|
||||
elif warn:
|
||||
raise Warning("Req is not ready!")
|
||||
|
||||
def from_file(self) -> bool:
|
||||
if exists("Config.json"):
|
||||
with open("Config.json", "r") as f:
|
||||
data = load(f)
|
||||
self.key_id = data["id"]
|
||||
self.key_sec = data["sec"]
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def to_file(self) -> None:
|
||||
data={"id":self.key_id, "sec":self.key_sec}
|
||||
with open("Config.json", "w") as f:
|
||||
dump(data,f)
|
||||
|
||||
def set(self,key_id: str, key_sec: str):
|
||||
self.key_id = key_id
|
||||
self.key_sec = key_sec
|
||||
self.ready = True
|
||||
self.to_file()
|
||||
super().__init__(key_id, key_sec)
|
||||
|
||||
def __call__(self,url:str,filename:str,**argvs) -> dict:
|
||||
with open(filename,"rb") as f:
|
||||
file=b64encode(f.read()).decode()
|
||||
parms=dict(image_base64=file,**argvs)
|
||||
ret=self.post(url,parms)
|
||||
# print(ret)
|
||||
return loads(ret)
|
4
change_font/requirements.txt
Normal file
4
change_font/requirements.txt
Normal file
@ -0,0 +1,4 @@
|
||||
opencv
|
||||
numpy
|
||||
matplotlib
|
||||
Pillow
|
21
change_font/temp.py
Normal file
21
change_font/temp.py
Normal file
@ -0,0 +1,21 @@
|
||||
from req import Req
|
||||
from json import dump
|
||||
import pickle
|
||||
from reportlab.pdfbase import pdfmetrics
|
||||
from reportlab.pdfbase import ttfonts
|
||||
from reportlab.pdfgen import canvas
|
||||
from reportlab.lib.units import mm
|
||||
|
||||
with open("data.conf","rb") as f:
|
||||
data=pickle.load(f)
|
||||
# with open("data.json","w",encoding="utf-8")as f:
|
||||
# dump(data,f)
|
||||
can=canvas.Canvas("file.pdf")
|
||||
pdfmetrics.registerFont(ttfonts.TTFont("st","C:\Windows\Fonts\STSONG.TTF"))
|
||||
for text in data["single_box"]["hand_text"]:
|
||||
pos=text["poses"]
|
||||
can.setFont("st",(pos[2]['y']-pos[0]['y'])/4)
|
||||
t=('#####'.join(text["texts"]))
|
||||
can.drawString(*text["poses"][0].values(),t)
|
||||
can.showPage()
|
||||
can.save()
|
0
change_font/util/__init__.py
Normal file
0
change_font/util/__init__.py
Normal file
36
change_font/util/get_ws_sign.py
Normal file
36
change_font/util/get_ws_sign.py
Normal file
@ -0,0 +1,36 @@
|
||||
from util.sign_client import get_signature
|
||||
from util.url import url_format,encode
|
||||
|
||||
|
||||
def get_sign(
|
||||
access_key_id,
|
||||
access_key_secret,
|
||||
timestamp,
|
||||
url,
|
||||
url_params):
|
||||
if access_key_id is None or len(access_key_id) == 0:
|
||||
raise RuntimeError('参数access_key_id不能为空')
|
||||
if access_key_secret is None or len(access_key_secret) == 0:
|
||||
raise RuntimeError('参数access_key_secret不能为空')
|
||||
if timestamp is None or len(timestamp) == 0:
|
||||
raise RuntimeError('参数timestamp不能为空')
|
||||
if url is None or len(url) == 0:
|
||||
raise RuntimeError('参数url不能为空')
|
||||
if url_params is None:
|
||||
raise RuntimeError('参数url_params不能为空')
|
||||
|
||||
url_params['access_key_id'] = access_key_id
|
||||
url_params['timestamp'] = timestamp
|
||||
|
||||
signature, signature_nonce = get_signature(
|
||||
url_params,
|
||||
None,
|
||||
'GET',
|
||||
'application/application_json',
|
||||
access_key_secret)
|
||||
|
||||
url_params["signature_nonce"] = signature_nonce
|
||||
url_params["signature"] = encode(signature)
|
||||
|
||||
url = url + '?' + url_format(url_params)
|
||||
return url
|
63
change_font/util/http.py
Normal file
63
change_font/util/http.py
Normal file
@ -0,0 +1,63 @@
|
||||
import requests
|
||||
|
||||
application_json = 'application/json'
|
||||
application_x_www_form_urlencoded = 'application/x-www-form-urlencoded'
|
||||
multipart_formdata = 'multipart/form-data'
|
||||
multipart_encoder = 'multipart_encoder'
|
||||
binary = 'binary'
|
||||
|
||||
|
||||
def send_delete(url, headers):
|
||||
response = requests.delete(url, headers=headers)
|
||||
return response.content.decode("utf-8")
|
||||
|
||||
|
||||
def send_get(url, params, headers):
|
||||
response = requests.get(url=url, params=params, headers=headers)
|
||||
return response.content.decode("utf-8")
|
||||
|
||||
|
||||
def send_post(url, request_body, headers):
|
||||
content_type = headers['content-type']
|
||||
if application_json == content_type:
|
||||
response = requests.post(url, json=request_body, headers=headers)
|
||||
elif multipart_formdata == content_type:
|
||||
data = get_multipart_data(request_body,headers)
|
||||
response = requests.post(url, data=data, headers=headers)
|
||||
else:
|
||||
response = requests.post(url, data=request_body, headers=headers)
|
||||
|
||||
return response.content.decode("utf-8")
|
||||
|
||||
|
||||
def send_put(url, request_body, headers):
|
||||
content_type = headers['content-type']
|
||||
if application_json == content_type:
|
||||
response = requests.put(url, json=request_body, headers=headers)
|
||||
elif multipart_formdata == content_type:
|
||||
data = get_multipart_data(request_body,headers)
|
||||
response = requests.put(url, data=data, headers=headers)
|
||||
else:
|
||||
response = requests.put(url, data=request_body, headers=headers)
|
||||
|
||||
return response.content.decode("utf-8")
|
||||
|
||||
|
||||
def send_patch(url, request_body, headers):
|
||||
content_type = headers['content-type']
|
||||
if application_json == content_type:
|
||||
response = requests.patch(url, json=request_body, headers=headers)
|
||||
elif multipart_formdata == content_type:
|
||||
data = get_multipart_data(request_body,headers)
|
||||
response = requests.patch(url, data=data, headers=headers)
|
||||
else:
|
||||
response = requests.patch(url, data=request_body, headers=headers)
|
||||
|
||||
return response.content.decode("utf-8")
|
||||
|
||||
|
||||
def get_multipart_data(request_body,headers):
|
||||
data = request_body['multipart_encoder']
|
||||
headers['content-type'] = data.content_type
|
||||
|
||||
return data
|
66
change_font/util/send_sign_http.py
Normal file
66
change_font/util/send_sign_http.py
Normal file
@ -0,0 +1,66 @@
|
||||
from util.http import send_patch,send_post,send_delete,send_get,send_put
|
||||
from util.sign_client import get_signature
|
||||
from util.url import encode,url_format
|
||||
|
||||
|
||||
def send_request(
|
||||
access_key_id,
|
||||
access_key_secret,
|
||||
timestamp,
|
||||
url,
|
||||
url_params,
|
||||
body_params,
|
||||
request_method,
|
||||
content_type
|
||||
) -> str:
|
||||
if access_key_id is None or len(access_key_id) == 0:
|
||||
raise RuntimeError('参数access_key_id不能为空')
|
||||
if access_key_secret is None or len(access_key_secret) == 0:
|
||||
raise RuntimeError('参数access_key_secret不能为空')
|
||||
if timestamp is None or len(timestamp) == 0:
|
||||
raise RuntimeError('参数timestamp不能为空')
|
||||
if url is None or len(url) == 0:
|
||||
raise RuntimeError('参数url不能为空')
|
||||
if url_params is None:
|
||||
raise RuntimeError('参数url_params不能为空')
|
||||
if body_params is None:
|
||||
raise RuntimeError('参数body_params不能为空')
|
||||
if request_method is None or len(request_method) == 0:
|
||||
raise RuntimeError('参数request_method不能为空')
|
||||
if content_type is None or len(content_type) == 0:
|
||||
raise RuntimeError('参数content_type不能为空')
|
||||
|
||||
url_params['access_key_id'] = access_key_id
|
||||
url_params['timestamp'] = timestamp
|
||||
|
||||
signature, signature_nonce = get_signature(
|
||||
url_params,
|
||||
body_params,
|
||||
request_method,
|
||||
content_type,
|
||||
access_key_secret)
|
||||
|
||||
url_params['signature'] = encode(signature)
|
||||
url_params['signature_nonce'] = signature_nonce
|
||||
url_params['timestamp'] = timestamp
|
||||
|
||||
url = url + '?' + url_format(url_params)
|
||||
|
||||
headers = {
|
||||
'content-type': content_type
|
||||
}
|
||||
|
||||
result = None
|
||||
if request_method == 'POST':
|
||||
result = send_post(url, request_body=body_params, headers=headers)
|
||||
elif request_method == 'PATCH':
|
||||
result = send_patch(url, request_body=body_params, headers=headers)
|
||||
elif request_method == 'PUT':
|
||||
result = send_put(url, request_body=body_params, headers=headers)
|
||||
elif request_method == 'GET':
|
||||
result = send_get(url, params=None, headers=headers)
|
||||
elif request_method == 'DELETE':
|
||||
result = send_delete(url, headers=headers)
|
||||
else:
|
||||
raise RuntimeError('支持[GET、POST、PUT、PATCH、DELETE]请求方式')
|
||||
return result
|
53
change_font/util/sign_client.py
Normal file
53
change_font/util/sign_client.py
Normal file
@ -0,0 +1,53 @@
|
||||
#!/usr/bin/python
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
import base64
|
||||
import hmac
|
||||
from hashlib import sha1
|
||||
import uuid
|
||||
from urllib import parse
|
||||
import json
|
||||
from util.url import url_format_list
|
||||
from util.http import application_x_www_form_urlencoded,application_json
|
||||
|
||||
__request_body = "request_body"
|
||||
|
||||
|
||||
def __generate_signature(parameters, access_key_secret):
|
||||
sorted_parameters = sorted(parameters.items(), key=lambda parameters : parameters[0])
|
||||
string_to_sign = url_format_list(sorted_parameters)
|
||||
secret = access_key_secret + "&"
|
||||
|
||||
# print(secret)
|
||||
h = hmac.new(secret.encode('utf-8'), string_to_sign.encode('utf-8'), sha1)
|
||||
signature = base64.b64encode(h.digest()).strip()
|
||||
signature = str(signature, encoding="utf8")
|
||||
# signature = bytes(signature, encoding="utf8")
|
||||
return signature
|
||||
|
||||
|
||||
def get_signature(url_params, body_params, request_method, content_type, access_key_secret):
|
||||
signature_nonce = str(uuid.uuid1())
|
||||
|
||||
sign_param = {
|
||||
'signature_nonce': signature_nonce
|
||||
}
|
||||
|
||||
if (content_type == application_x_www_form_urlencoded or content_type == application_json) \
|
||||
and (request_method == 'POST' or request_method == 'PATCH' or request_method == 'PUT')\
|
||||
and body_params is not None and len(body_params) != 0:
|
||||
if content_type == application_x_www_form_urlencoded:
|
||||
sign_param[__request_body] = parse.urlencode(body_params)
|
||||
else:
|
||||
sign_param[__request_body] = json.dumps(body_params)
|
||||
# 生成签名使用Python,发送签名使用其他语言时使用separators
|
||||
# sign_param[__request_body] = json.dumps(body_params,separators=(',',':'))
|
||||
|
||||
for key in url_params.keys():
|
||||
sign_param[key] = url_params[key]
|
||||
|
||||
signature = __generate_signature(sign_param, access_key_secret)
|
||||
return signature, signature_nonce
|
||||
|
||||
|
||||
|
24
change_font/util/url.py
Normal file
24
change_font/util/url.py
Normal file
@ -0,0 +1,24 @@
|
||||
from urllib.parse import quote
|
||||
|
||||
|
||||
def encode(val):
|
||||
val = quote(val, 'utf-8')
|
||||
return val
|
||||
|
||||
|
||||
def url_format_list(parameters):
|
||||
param_list = []
|
||||
for (k, v) in parameters:
|
||||
param_str = '{}={}'.format(k, v)
|
||||
param_list.append(param_str)
|
||||
string_to_sign = '&'.join(param_list)
|
||||
return string_to_sign
|
||||
|
||||
|
||||
def url_format(parameters):
|
||||
param_list = []
|
||||
for key, value in parameters.items():
|
||||
param_str = '{}={}'.format(key, value)
|
||||
param_list.append(param_str)
|
||||
string_to_sign = '&'.join(param_list)
|
||||
return string_to_sign
|
Reference in New Issue
Block a user