def Send(chatroom, sender=None, name='random', top='_', bot='_', font='impact', img=''): if name == 'random': rand = GetRandomTemplate(chatroom, sender) name = rand[0] img = rand[1] elif name == "custom": if IsEmpty(img): raise Exception("img is empty") else: if IsEmpty(img): img = GetImg(chatroom, sender, name) if IsEmpty(img): if name not in builtinTemplates: chatroom.SendText("[Command(Meme)] Template named '" + name + "' not found") return CommandResult.Done() else: name = "custom" top = Escape(top) bot = Escape(bot) if IsEmpty2(top) and IsEmpty2(bot) and not IsEmpty(img): return CommandResult(images=Image(client=chatroom.client, url=img)) url = GetUrl(name, top, bot, font, img) return CommandResult( images=Image(client=chatroom.client, url="https://" + url))
def __init__(self, client, id, chatroom, receiver, sender=None, url=None, bytes=None): ContentMessage.__init__(self, client, id, chatroom, receiver, sender, url, bytes) self.contentType = ContentType.IMAGE self.content = Image(client=client, message=self, url=url, bytes=bytes)
def JPEG(message, options, images=[], quality=50, iterations=50): img = images[0].bytes imgIn = BytesIO(img) baseQuality=quality for i in range(0, iterations): #open previously generated file compImg = PILImage.open(imgIn) #compress file at 50% of previous quality imgOut = BytesIO() compImg.save(imgOut, "JPEG", quality=quality) quality = int(quality*baseQuality/100) imgIn = imgOut imgIn.seek(0) img = imgIn.read() img = Image(bytes=img) return CommandResult.Done(images=[img])
def DeepArtCustom(message, images): s = Session() print("Getting token ...") rToken = s.get(daLoginUrl, verify=False) mToken = daTokenRx.match(rToken.text) token = mToken.group(1) print("Logging in ...") info = {'csrfmiddlewaretoken': token, 'email': daEmail, 'password': daPw} rLogin = s.post(daLoginUrl, verify=False) print("Uploading image ...") img = images[1].bytes rImg = s.post(daContentUploadUrl, files={'image': img}, verify=False) jImg = loads(rImg.text) print("Uploading style ...") style = images[0].bytes rStyle = s.post(daStyleUploadUrl, files={'image': style}, verify=False) jStyle = loads(rStyle.text) print("Requesting ...") info = { 'content_img': jImg['hash'], 'style_img': jStyle['hash'], 'email': daEmail, 'password': daPw, 'privacy': 'private' } rDa = s.post(daUrl, data=info, verify=False) jDa = loads(rDa.text) rDa = s.post(daHomeUrl + jDa['redirect'], verify=False) mDaCode = daCodeRx.match(rDa.text) daCode = mDaCode.group(1) daCodeUrl = daHost + daCode + "/" message.ReplyText("[DeepArt] Please wait up to 15 minutes.\n" + daCodeUrl) while True: rDaCode = s.get(daCodeUrl, verify=False) if rDaCode.url == daCodeUrl: mDaImg = daImgRx.match(rDaCode.text) daImg = mDaImg.group(1) img = Image(url=daImg) return CommandResult.Done(images=[img]) sleep(5)
def DeepArtBuiltin(message, style, images): if not style.isdigit(): message.ReplyText("Invalid style (1)") return CommandResult.Failed() r = post( 'http://turbo.deepart.io/api/post/', data={ 'style': style, 'return_url': 'http://my.return/' }, files={'input_image': ('file.jpg', images[0].bytes, 'image/jpeg')}) img = r.text if len(img) > 100: message.ReplyText("Invalid style (2)") return CommandResult.Failed() path = ("/media/output/%s.jpg" % img) link = "https://turbo.deepart.io" + path message.ReplyText("[DeepArt] Please wait up to 3 minutes.\n" + link) WaitOK("turbo.deepart.io", path) img = Image(url=link) return CommandResult.Done(images=[img])
def DeepStyle(message, options, images=[]): print("Getting session") s = Session() s.auth = (dsEmail, dsPw) s.headers.update({'User-Agent' : str(UserAgent().chrome)}) print("Getting token") rToken = s.get(dsLoginUrl) if rToken.status_code != 200: message.ReplyText("Error DS 1") return CommandResult.Failed() mToken = dsTokenRx.match(rToken.text) token = mToken.group(1) info = {"_token":token, "email":dsEmail, "password":dsPw, "remember":"true"} print("Logging in") rLogin = s.post(dsLoginUrl, data=info) if rLogin.status_code != 200: message.ReplyText("Error DS 2") return CommandResult.Failed() TryChangeToken(rLogin.text, info) rDeepStyle = s.get(dsUrl, data=info) if rDeepStyle.status_code != 200: message.ReplyText("Error DS 3") return CommandResult.Failed() info = {"_token":info["_token"]} TryChangeToken(rDeepStyle.text, info) print("Getting images") style = images[0].bytes img = images[1].bytes print("Requesting deepstyle") info["style"] = "custom" info["dreamType"]="deep-style" info["resolution"]="normal" info["optimizer"]="alpha" info["iterationsDepth"] ="normal" info["preserveOriginalColors"]="no" info["access"] = "public" info["styleScale"] = "1" info["styleWeight"] = "5" rUploadImg = s.post(dsUploadUrl, data=info, files={'image':img, 'styleImage':style}) if rUploadImg.status_code != 200: message.ReplyText("Error DS 4\n" + rUploadImg.text) return CommandResult.Failed() mDsLink = dsLinkRx.match(rUploadImg.text) if mDsLink is None: message.ReplyText("Error DS 5 : '" + dsErrorRx.match(rUploadImg.text).group(1).replace('"', '"') + "'") return CommandResult.Failed() while mDsLink is None: time.sleep(300) rUploadImg = s.post(dsUploadUrl, data=info, files={'image':img, 'styleImage':style}) if rUploadImg.status_code != 200: message.ReplyText("Error DS 6") return CommandResult.Failed() mDsLink = dsLinkRx.match(rUploadImg.text) dsLink = mDsLink.group(1) message.ReplyText("[DeepStyle] Please wait up to 5 minutes\n" + dsLink) mDsLinkParse = dsLinkParseRx.match(dsLink) host = mDsLinkParse.group(1) path = mDsLinkParse.group(2) WaitOK(host, path) img = Image(url=dsLink) return CommandResult.Done(images=[img])
def Activate(message, options, name, admin=False, activate=True): mode = 0 if admin: mode = 10 elif 'r' in options: mode = 1 elif 's' in options: mode = 2 s = 'a' if not activate: s = 'dea' sT = 'A' if not activate: sT = 'Dea' sDate = 'NULL' if not activate: sDate = 'NOW()' if not message.sender: if mode == 0: message.ReplyText( "[Command(Meme)] Unfortunately we can't identify you so only room meme template named '%s' will be %sctivated if exists" % (name, s)) mode = 1 elif mode == 2: message.ReplyText( "[Command(Meme)] Unfortunately we can't identify you so your request can't be fulfilled." ) return CommandResult.Done() cur = message.client.GetCursor() f = None if mode == 10: cur.Execute( "UPDATE CustomMemes SET deactivationDatetime=" + sDate + " WHERE name=%s RETURNING imageUrl, description", (name, )) if cur.rowCount == 0: message.ReplyText( "[Command(Meme)] %sctivating global meme template failed, template named '%s' not found" % (sT, name)) return CommandResult.Done() f = cur.FetchOne() if activate: return RegisterMeme(message, name=name, images=[Image(url=f[0])], desc=f[1], mode=mode, options=options, insert=False) fr = None if mode == 0 or mode == 1: rId = message.chatroom._2id cur.Execute( "UPDATE RoomCustomMemes SET deactivationDatetime=" + sDate + " WHERE rId=%s AND name=%s RETURNING imageUrl, description", ( rId, name, )) if cur.rowCount == 0: message.ReplyText( "[Command(Meme)] %sctivating room meme template failed, template named '%s' not found" % (sT, name)) if mode == 1: return CommandResult.Done() else: fr = cur.FetchOne() if mode == 1: cur.Commit() if activate: return RegisterMeme(message, name=name, images=[Image(url=fr[0])], desc=fr[1], mode=1, options=options, insert=False) fs = None if mode == 0 or mode == 2: uId = message.chatroom._2id cur.Execute( "UPDATE UserCustomMemes SET deactivationDatetime=" + sDate + " WHERE uId=%s AND name=%s RETURNING imageUrl, description", ( uId, name, )) if cur.rowCount == 0: message.ReplyText( "[Command(Meme)] %sctivating user meme template failed, template named '%s' not found" % (sT, name)) if mode == 2: return CommandResult.Done() else: fs = cur.FetchOne() if mode == 2: cur.Commit() if activate: return RegisterMeme(message, name=name, images=[Image(url=fs[0])], desc=fs[1], mode=2, options=options, insert=False) cur.Commit() if activate: return _1Activate(message, name, fr, fs) return _1Deactivate(message, name, f, fr, fs)
def _1Activate(message, name, fr, fs): if fr: if fs: rUrl = fr[0] rDesc = fr[1] sUrl = fs[0] sDesc = fs[1] if rUrl == sUrl and rDesc == sDesc: return RegisterMeme(message, name=name, images=[Image(url=rUrl)], desc=rDesc, mode=0, options=options, insert=False) else: rRes = RegisterMeme(message, name=name, images=[Image(url=rUrl)], desc=rDesc, mode=1, options=options, insert=False) sRes = RegisterMeme(message, name=name, images=[Image(url=sUrl)], desc=sDesc, mode=2, options=options, insert=False) if rRes.images: if sRes.images: return CommandResult.Done(images=rRes.images + sRes.images) return rRes elif sRes.images: return sRes else: rTexts = rRes.texts sTexts = sRes.texts if rTexts: if sTexts: return CommandResult.Done(texts=rTexts + sTexts) return rRes elif sTexts: return sRes return CommandResult.Done(texts=["Unknown Error"]) else: return RegisterMeme(message, name=name, images=[Image(url=fr[0])], desc=fr[1], mode=1, options=options, insert=False) elif fs: return RegisterMeme(message, name=name, images=[Image(url=fs[0])], desc=fs[1], mode=2, options=options, insert=False) return CommandResult.Done()
def LunaPic(message, options, text='', images=[]): link = images[0].imgurUrl splitArgs = text.split(' ') if splitArgs[0] == 'random': if len(splitArgs) < 1 or isEmpty(splitArgs[1]) or not splitArgs[1].isdigit(): iterations = 1 else: iterations = int(splitArgs[1]) if iterations < 1: iterations = 1 if iterations > 20: iterations = 20 #l = list(lpRandoms) splitArgs = [] for i in range(0, iterations): #splitArgs.append(l.pop(randint(0, len(l) - 1))) splitArgs.append(lpRandoms[randint(0,maxLpRandomIndex)]) print(str(splitArgs)) s = Session() r0 = s.get("http://lunapic.com/editor/?action=" + splitArgs[0] + "&url=" + link) if r0.status_code != 200: message.ReplyText("Error LP 1. LunaPic is probably down. Please try again later.") return lp0m = lprx0.match(r0.url) if lp0m is None: #print(r0.text) message.ReplyText("Error LP 2. LunaPic is probably down. Please try again later.") return lpurl = 'http://' + lp0m.group(1) + '/editor/' for arg0 in splitArgs: arg1 = arg0.split(':') arg = arg1[0] if arg not in lpActions: continue arg2 = None if len(arg1) > 1: arg2 = arg1[1] info = {'action':arg, 'url':link} if arg == 'tint' or arg == 'groovy-color': if arg2 is None: arg2 = lpColors[randint(0, maxLpColorIndex)] info['color'] = arg2 if arg == 'transitions': if arg2 is None: arg2 = lpTransitions[randint(0, maxLpTransitionIndex)] info['type'] = arg2 if arg == 'scan': if arg2 is None: arg2 = 1 info['hoz'] = arg2 r1 = s.post(lpurl, data=info) if r1.status_code != 200: message.ReplyText("Error LP 3. LunaPic is probably down\n" + "lpurl='" + lpurl + "'\ninfo='" + str(info) + "'") return CommandResult.Failed() r2a = s.get(lpurl + "?action=imgur") if r2a.status_code != 200: message.ReplyText("Error LP 4. LunaPic is probably down\n" + "lpurl='" + lpurl + "'\ninfo='" + str(info) + "'") return CommandResult.Failed() mLpimgurRx = lpimgurRx.match(r2a.text) if mLpimgurRx is None: message.ReplyText("Error LP 5. LunaPic is probably down or you submitted invalid action\n" + "lpurl='" + lpurl + "'\ninfo='" + str(info) + "'") return CommandResult.Failed() link = mLpimgurRx.group(1).replace("http:", "https:") img = Image(url=link) return CommandResult.Done(images=[img])
def DeepFry(message, options, images=[], quality=90, iterations=3, pixel=0.95, iterations2=3, tint="rgb(255,160,100)"): img = images[0].bytes imgIn = BytesIO(img) baseQuality = quality scale = pixel secondIter = iterations2 tintColor = tint quality = baseQuality img = PILImage.open(imgIn) for i in range(0, iterations): img = ImageEnhance.Contrast(img).enhance(2) img = ImageEnhance.Sharpness(img).enhance(2) img = ImageEnhance.Contrast(img).enhance(2) img = img.filter(ImageFilter.SHARPEN) img = ImageEnhance.Contrast(img).enhance(2) img = img.filter(ImageFilter.EDGE_ENHANCE) img = ImageEnhance.Contrast(img).enhance(2) #img = img.filter(ImageFilter.EDGE_ENHANCE_MORE) imgOut = BytesIO() img.save(imgOut, "JPEG", quality=quality) quality = int(quality * baseQuality / 100) imgOut.seek(0) img = PILImage.open(imgOut) quality = baseQuality if scale < 1: ori = (img.width, img.height) img = img.resize((int(img.width * scale), int(img.height * scale))) img = Tint(img, tintColor) img = ImageEnhance.Sharpness(img).enhance(2) img = img.filter(ImageFilter.SHARPEN) img = img.filter(ImageFilter.EDGE_ENHANCE) img = ImageEnhance.Sharpness(img).enhance(2) img = img.filter(ImageFilter.SHARPEN) img = ImageEnhance.Contrast(img).enhance(2) img = ImageOps.autocontrast(img) if scale < 1: img = img.resize(ori, PILImage.NEAREST) imgOut = BytesIO() img.save(imgOut, "JPEG", quality=quality) imgOut.seek(0) img = PILImage.open(imgOut) for i in range(0, secondIter): imgOut = BytesIO() img.save(imgOut, "JPEG", quality=quality) quality = int(quality * baseQuality / 100) imgOut.seek(0) img = PILImage.open(imgOut) imgOut = BytesIO() img.save(imgOut, "JPEG", quality=quality) imgOut.seek(0) img = imgOut.read() img = Image(bytes=img) return CommandResult.Done(images=[img])