1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| import requests import json import sys import re import os from prettytable import PrettyTable
if sys.platform.startswith('win'): dir_char = '\\' else: dir_char = '/'
def post_img(filePath): headers = { 'Authorization': 'MEQCiM6viKEEF8RYPRIpOL4DA7oGtwvA', } try: data = { 'smfile': (filePath.split('/')[-1], open(filePath, 'rb')), 'format': 'json' } except: return False res = requests.post('https://sm.ms/api/v2/upload', headers=headers, files=data).text return json.loads(res)
def get_path(rt, rel): return os.path.abspath(rt+rel)
def format_markdown(filePath): _user_path = os.path.expanduser('~') rt_path = dir_char.join(os.path.abspath(filePath).split(dir_char)[:-1]) + dir_char tb = PrettyTable() tb.field_names = ['File', 'Status', 'url'] img_set = {} with open(filePath, 'r') as fp: ct = fp.read() aims = re.findall('!\[.*?\]\((.*?)\)', ct, re.M) for aim in aims: raw_path = aim aim = aim.replace('~', _user_path) aim = aim if aim.startswith(dir_char) else get_path(rt_path, aim) if aim not in img_set: res = post_img(aim) if not res: tb.add_row([aim.split(dir_char)[-1], 'No File', '']) img_set[aim] = False else: tb.add_row([aim.split(dir_char)[-1], res['success'], '' if not res['success'] else res['data']['url']]) img_set[aim] = res['data']['url'] if img_set[aim]: ct = ct.replace(raw_path, img_set[aim]) with open(filePath, 'w') as fp: fp.write(ct) print(tb)
if __name__ == '__main__': format_markdown(sys.argv[1])
|