class ImgurClient: def __init__(self, client_id, access_token): self.ic = Imgur({'client_id': client_id, 'access_token': access_token}) def create_album(self, name: str): print("creating album: ", name) album = self.ic.album_create([], name, '', 'public') album_id = album['response']['data']['id'] return album_id def upload_gif(self, path: str, title: str = None, desc: str = None, album_hash: str = None): print("uploading ", path) response = self.ic.image_upload(filename=path, title=title, description=desc, album=album_hash) return response def upload_folder(self, path: str): error_status = {} album_name = path.split("\\")[-1] album_id = self.create_album(album_name) all_files = glob.glob(path + "\\*") for file in all_files: file_name = file.split("\\")[-1] status = self.upload_gif(path=file, title=file_name, album_hash=album_id) if status["status"] != 200: msg = { "status": status, "file": file_name, "next": "retry upload in an hour" } ctypes.windll.user32.MessageBoxW(0, msg, "Error", 1) time.sleep(3600) status = self.upload_gif(path=file, title=file_name, album_hash=album_id) if status["status"] == 200: msg = f'File {file_name} upload successfully continued' ctypes.windll.user32.MessageBoxW(0, msg, "OK", 1) error_status[file] = status return error_status
def My_Object_Detection(url, filename): SUBSCRIPTION_KEY = os.getenv('Object_Detection_KEY') ENDPOINT = os.getenv('Object_Detection_ENDPOINT') CV_CLIENT = ComputerVisionClient( ENDPOINT, CognitiveServicesCredentials(SUBSCRIPTION_KEY)) IMGUR_CONFIG = { "client_id": os.getenv('IMGUR_Client_ID'), "client_secret": os.getenv('IMGUR_Client_Secret'), "access_token": os.getenv('Postman_Access_Token'), "refresh_token": os.getenv('Postman_Refresh_token') } IMGUR_CLIENT = Imgur(config=IMGUR_CONFIG) img = Image.open(filename) draw = ImageDraw.Draw(img) font_size = int(5e-2 * img.size[1]) fnt = ImageFont.truetype("./font/TaipeiSansTCBeta-Regular.ttf", size=font_size) object_detection = CV_CLIENT.detect_objects(url) # create detection_object if len(object_detection.objects) > 0: for obj in object_detection.objects: left = obj.rectangle.x top = obj.rectangle.y right = obj.rectangle.x + obj.rectangle.w bot = obj.rectangle.y + obj.rectangle.h name = obj.object_property # prediction of object confidence = obj.confidence draw.rectangle([left, top, right, bot], outline=(255, 0, 0), width=3) draw.text( [left, top + font_size], "{0} {1:0.1f}".format(name, confidence * 100), fill=(255, 0, 0), font=fnt, ) img.save(filename) image = IMGUR_CLIENT.image_upload(filename, "title", "description") link = image["response"]["data"]["link"] os.remove(filename) return link
def cc_entry(): try: req_data = request.get_json() image = req_data["cc-image"] if image[0:12] == "data:image/p": ext = ".png" else: ext = ".jpg" del (req_data["cc-image"]) filename, m = urlretrieve(image) print(filename) print(ext) print(req_data) # imgur upload stuff imgur_client = Imgur(app.env_vars["imgur"]) file = path.realpath(filename) title = 'new entry' description = 'new entry' album = 'YUE0mAD' childname_list = list(req_data["cc-childs-name"]) childname_list[0] = childname_list[0].upper() childname = "".join(childname_list) response = imgur_client.image_upload(file, title, description, album) img_id = response['response']['data']['id'] response = imgur_client.image_update( img_id, "Entry: " + img_id, "Entry ID: " + img_id + " \n" + childname + " Age: " + str(req_data["cc-childs-age"])) print(response) new_entry = SPEntry(id=img_id, email=req_data["cc-email"], adults_name=req_data["cc-adults-name"], childs_name=childname, childs_age=req_data["cc-childs-age"], image=img_id, mailing_list=req_data["cc-mail-list"]) db.session.add(new_entry) db.session.commit() except Exception as e: print(e) return {"response_code": 500} return {"response_code": 200}
def showImgurP(fileName): imgur_client = Imgur({ 'client_id': client_id, 'access_token': access_token }) # 開始上傳檔案 try: # print("[log:INFO]Uploading image... ") imgurla = imgur_client.image_upload( path.realpath('./' + fileName + '.png'), 'Untitled', 'My first image upload') image_id = imgurla['response']['data']['id'] # string to dict print("[log:INFO]Done upload. ") # print(imgurl) imgurl = 'https://i.imgur.com/' + image_id + '.png' except: # 如果失敗回傳"失敗"這張圖 imgurl = 'https://i.imgur.com/RFmkvQX.jpg' print("[log:ERROR]Unable upload ! ") return imgurl
FACE_KEY = os.getenv('FACE_KEY') FACE_END = os.getenv('FACE_END') LINE_SECRET = os.getenv('LINE_SECRET') LINE_TOKEN = os.getenv('LINE_TOKEN') IMGUR_CONFIG = { "client_id": os.getenv('IMGUR_ID'), "client_secret": os.getenv('IMGUR_SECRET'), "access_token": os.getenv('IMGUR_ACCESS'), "refresh_token": os.getenv('IMGUR_REFRESH') } CV_CLIENT = ComputerVisionClient( ENDPOINT, CognitiveServicesCredentials(SUBSCRIPTION_KEY)) LINE_BOT = LineBotApi(LINE_TOKEN) HANDLER = WebhookHandler(LINE_SECRET) IMGUR_CLIENT = Imgur(config=IMGUR_CONFIG) def azure_describe(url): """ Output azure image description result """ description_results = CV_CLIENT.describe_image(url) output = "" for caption in description_results.captions: output += "'{}' with confidence {:.2f}% \n".format( caption.text, caption.confidence * 100) return output class AzureImageOutput():
def __init__(self, client_id, access_token): self.ic = Imgur({'client_id': client_id, 'access_token': access_token})
TextSendMessage, FlexSendMessage, ImageSendMessage) from linebot.models.flex_message import BubbleContainer, ImageComponent from linebot.models.actions import URIAction # 讀取相關服務的token資訊 secretFile = json.load(open('secretFile.json', 'r')) # 讀取LineBot驗證資訊 line_bot_api = LineBotApi(secretFile['line']['channelAccessToken']) handler = WebhookHandler(secretFile['line']['channelSecret']) # 建立Imgur API imgurClient = Imgur(config={ "client_id": secretFile['imgur']['client_id'], "client_secret": secretFile['imgur']['client_secret'], "access_token": secretFile['imgur']['access_token'], "refresh_token": secretFile['imgur']['refresh_token'] }) # 啟用Azure人臉偵測服務 azureFaceKey = secretFile['azure_face']['key'] azureFaceEndpoint = secretFile['azure_face']['endpoint'] face_client = FaceClient(azureFaceEndpoint, CognitiveServicesCredentials(azureFaceKey)) # 啟用Azure電腦視覺服務 azureCvKey = secretFile['azure_cv']['key'] azureCvEndpoint = secretFile['azure_cv']['endpoint'] cv_client = ComputerVisionClient(azureCvEndpoint, CognitiveServicesCredentials(azureCvKey)) # 設定輸出字體 ttf_path = "./font/TaipeiSansTCBeta-Regular.ttf"
# image = client.upload_from_path(image_path, config=config, anon=False) image = client.image_upload( image_path, cardid, f'cardImage with random colors - {datetime.now()}') return image client_config = { 'client_id': 'a5c95a6a3f96f21', 'client_secret': '53e0ddb945dd43798999a1541845f1a41a37be79', 'access_token': "8c4c79ab45e1d2d2f033c1a4488dda93b42aa9f6", 'refresh_token': "25de927417108bb9deecad7ebaf2f400f16177e1" } # client = ImgurClient(client_id, client_secret, access_token, refresh_token) client = Imgur(client_config) with open('cards_new.json', encoding="utf-8") as json_file: cards = json.load(json_file) for c in cards: # print('id: ' + c['id']) # print('Name: ' + c['cardname']) # image = draw_card(c['cardname']) # image.save(f"cards/{c['id']}.png") if (c['cardimage'] == None): image_url = upload_image(client, c['cardname'], c['id'], f"cards/{c['id']}.png") # c['cardimage'] = image_url['link'] c['cardimage'] = image_url['response']['data']['link'] sleep(2)
image = IMGUR_CLIENT.image_upload(filename, "title", "description") link = image["response"]["data"]["link"] os.remove(filename) return link if __name__ == "__main__": # 爬取網站圖片,並儲存於本地端 uri = 'https://anntw-prod.s3.amazonaws.com/assets/images/000/020/997/big/crocodile-817680_640.jpg' res = requests.get(uri).content filename = './image/test.jpg' with open(filename, 'wb') as f: f.write(res) IMGUR_CONFIG = { "client_id": os.getenv('IMGUR_Client_ID'), "client_secret": os.getenv('IMGUR_Client_Secret'), "access_token": os.getenv('Postman_Access_Token'), "refresh_token": os.getenv('Postman_Refresh_token') } IMGUR_CLIENT = Imgur(config=IMGUR_CONFIG) image = IMGUR_CLIENT.image_upload(filename, "title", "description") url = image["response"]["data"]["link"] result = My_Object_Detection(url, filename) print(result)