async def withTag(tags, id): id = str(UUID(id)) #media = MediaWarehouse.getMetadata(id=id) media = Media.select(Media.id, Media.extension, Media.mainDescription, Media.additionalData, Media.created, Media.lastHit, Media.sourceType, Media.source).where(Media.id==id).get() '''url = MediaWarehouse.convertURL(media['id']) thumb = MediaWarehouse.convertThumbnailURL(media['id']) thumbRetina = MediaWarehouse.convertThumbnailRetinaURL(media['id']) pixiv = json.loads(media['additionalData'])['pixiv_v2'] now = datetime.datetime.now().timestamp() popularTags, tagToCount = MediaWarehouse.popularTags(20)''' url = MediaWarehouse.convertURL(media.id) thumb = MediaWarehouse.convertThumbnailURL(media.id) thumbRetina = MediaWarehouse.convertThumbnailRetinaURL(media.id) pixiv = json.loads(media.additionalData)['pixiv_v2'] now = datetime.datetime.now().timestamp() popularTags, tagToCount = MediaWarehouse.popularTags(20) return await render_template("pixiv_bytag.html", pixiv=pixiv, url=url, thumb=thumb, thumbRetina=thumbRetina, source=media.source, now=now, tags=tags.split(" ") if len(tags) > 0 else [""], popularTags=popularTags, tagToCount=tagToCount)
async def getImage(sourceType="PIXIV", **args): media = MediaWarehouse.getMetadata(sourceType=sourceType, random=True, **args) allTags = MediaWarehouse.listTags(media['id']) mainTag = allTags[0] if len(allTags) > 0 else " " return MediaWarehouse.convertThumbnailURL( media['id']), "https://wakeupscrew.catlee.se/tag/{}/{}".format( urllib.parse.quote(mainTag), media['id']), media['source'], json.loads( media['additionalData'])['pixiv_v2']
def getRandomCat(): try: while True: headers = {'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0'} source = urllib.request.urlopen(urllib.request.Request("https://cataas.com/cat", headers=headers), timeout=5) extension = guess_extension(source.info()['Content-Type']) if extension not in ["gif"]: extension = ".jpg" if extension == '.jpe' else extension extension = extension[1:] data = source.read() url = MediaWarehouse.convertURL(MediaWarehouse.create(data=data, thumbnail=data, extension=extension, mainDescription="CATAAS-{}".format(datetime.datetime.now()), source="https://cataas.com/cat", sourceType='CATAAS')['id']) return url except: return MediaWarehouse.convertURL(MediaWarehouse.get(sourceType='404', random=True)['id'])
async def getImageByTag(tags, tagOr=True, **args): media = MediaWarehouse.getMetadata(tags=tags, tagOr=tagOr, random=True, **args) matchTags = list( filter(lambda x: x in tags, MediaWarehouse.listTags(media['id']))) mainTag = (matchTags[0] if len(matchTags) > 0 else MediaWarehouse.listTags( media['id'])[0]) if tagOr else " ".join(tags) return MediaWarehouse.convertThumbnailURL( media['id']), "https://wakeupscrew.catlee.se/tag/{}/{}".format( urllib.parse.quote(mainTag), media['id']), media['source'], json.loads( media['additionalData'])['pixiv_v2']
async def getRandomCatAsync(): try: headers = {'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0'} async with aiohttp.ClientSession(headers=headers, timeout=aiohttp.ClientTimeout(total=5)) as session: async with session.get("https://cataas.com/cat") as source: extension = guess_extension(source.headers['Content-Type']) if extension not in [".gif"]: extension = ".jpg" if extension == '.jpe' else extension extension = extension[1:] data = await source.read() url = MediaWarehouse.convertURL(MediaWarehouse.create(data=data, thumbnail=data, extension=extension, mainDescription="CATAAS-{}".format(datetime.datetime.now()), source="https://cataas.com/cat", sourceType='CATAAS')['id']) return url except Exception as e: return None
async def getAllImage(num, **args): limit = datetime.datetime.now() - datetime.timedelta(days=EXPIRE_LIMIT) medias = MediaWarehouse.searchMetadata(limit=num, created=limit, random=True, **args) sets = [] for media in medias: mainTag = MediaWarehouse.listTags(media['id'])[0] sets.append([ MediaWarehouse.convertThumbnailURL(media['id']), "https://wakeupscrew.catlee.se/tag/{}/{}".format( urllib.parse.quote(mainTag), media['id']), media['source'], json.loads(media['additionalData'])['pixiv_v2'] ]) return sets
async def getPoliceWrappers(num): medias = MediaWarehouse.searchMetadata(sourceType="POLICEDEP", random=True, limit=num) print(medias) return [ BubbleContainer( direction='ltr', spacing='none', hero=ImageComponent( url=MediaWarehouse.convertThumbnailURL(media['id']), size='full', aspect_ratio="1:1", aspect_mode='cover', action=URIAction(label='FULL', uri=json.loads( media["additionalData"])["link"]), ), body=BoxComponent( layout='vertical', spacing='none', contents=[ BoxComponent( layout='vertical', margin='none', spacing='none', contents=[ BoxComponent( layout='baseline', spacing='none', contents=[ TextComponent( text=media['mainDescription'], size='xxs', weight="bold", flex=5) ], ), ], ), ], )) for media in medias ]
async def getWayfishSay(text): media = MediaWarehouse.get(sourceType="WAYFISHSAY_1", mainDescription=text) if media is not None: url = MediaWarehouse.convertURL(media['id']) thumbnailURL = MediaWarehouse.convertThumbnailURL(media['id']) return url, thumbnailURL watermark = Image.new('RGBA', (2592, 1936), (0, 0, 0, 0)) draw = ImageDraw.Draw(watermark) image = Image.open('wayfishsay.jpg') if drawTextInBox(text, [1650, 0], [942, 860], draw, fontsize=512, color=(255, 255, 255, 255), weight='black') == False: return False, False mask = ImageEnhance.Brightness(watermark).enhance(0) image.paste(watermark, (0, 0), mask) data = io.BytesIO() image.save(data, format='JPEG', quality=85) data = data.getvalue() thumb = ImageOps.fit(image, [1296, 968], Image.ANTIALIAS) thumbnail = io.BytesIO() thumb.save(thumbnail, format='JPEG', quality=85) thumbnail = thumbnail.getvalue() media = MediaWarehouse.create(sourceType="WAYFISHSAY_1", mainDescription=text, data=data, thumbnail=thumbnail, tags=['wayfishsay', 'wayfishsay_1'], extension='jpg') url = MediaWarehouse.convertURL(media['id']) thumbnailURL = MediaWarehouse.convertThumbnailURL(media['id']) return url, thumbnailURL
async def getMapoSay(text): media = MediaWarehouse.get(sourceType="MAPOSAY_1", mainDescription=text) if media is not None: url = MediaWarehouse.convertURL(media['id']) thumbnailURL = MediaWarehouse.convertThumbnailURL(media['id']) return url, thumbnailURL watermark = Image.new('RGBA', (1706, 960), (0, 0, 0, 0)) draw = ImageDraw.Draw(watermark) image = Image.open('maposay.jpg') if drawTextInBox(text, [1080, 0], [626, 960], draw, fontsize=256, color=(255, 255, 255, 200), weight='black') == False: return False, False mask = ImageEnhance.Brightness(watermark).enhance(0.2) image.paste(watermark, (0, 0), mask) data = io.BytesIO() image.save(data, format='JPEG', quality=85) data = data.getvalue() thumb = ImageOps.fit(image, [853, 480], Image.ANTIALIAS) thumbnail = io.BytesIO() thumb.save(thumbnail, format='JPEG', quality=85) thumbnail = thumbnail.getvalue() media = MediaWarehouse.create(sourceType="MAPOSAY_1", mainDescription=text, data=data, thumbnail=thumbnail, tags=['maposay', 'maposay_1'], extension='jpg') url = MediaWarehouse.convertURL(media['id']) thumbnailURL = MediaWarehouse.convertThumbnailURL(media['id']) return url, thumbnailURL
async def getCHCSay3(text): media = MediaWarehouse.get(sourceType="CHCSAY_3", mainDescription=text) if media is not None: url = MediaWarehouse.convertURL(media['id']) thumbnailURL = MediaWarehouse.convertThumbnailURL(media['id']) return url, thumbnailURL FONTSIZE = 144 watermark = Image.new('RGBA', (3024, 4032), (0, 0, 0, 0)) draw = ImageDraw.Draw(watermark) image = Image.open('chcsay3.jpg') if drawTextInBox(text, [70, 1550], [2870, 1250], draw, fontsize=640, color=(255, 255, 255, 255), weight='black', background=(0, 0, 0, 220)) == False: return False, False mask = ImageEnhance.Brightness(watermark).enhance(0.2) image.paste(watermark, (0, 0), mask) data = io.BytesIO() image.save(data, format='JPEG', quality=85) data = data.getvalue() thumb = ImageOps.fit(image, [960, 540], Image.ANTIALIAS) thumbnail = io.BytesIO() thumb.save(thumbnail, format='JPEG', quality=85) thumbnail = thumbnail.getvalue() media = MediaWarehouse.create(sourceType="CHCSAY_3", mainDescription=text, data=data, thumbnail=thumbnail, tags=['chcsay', 'chcsay_3'], extension='jpg') url = MediaWarehouse.convertURL(media['id']) thumbnailURL = MediaWarehouse.convertThumbnailURL(media['id']) return url, thumbnailURL
async def getCHCSay(text): media = MediaWarehouse.get(sourceType="CHCSAY_1", mainDescription=text) if media is not None: url = MediaWarehouse.convertURL(media['id']) thumbnailURL = MediaWarehouse.convertThumbnailURL(media['id']) return url, thumbnailURL FONTSIZE = 144 watermark = Image.new('RGBA', (1920, 1080), (0, 0, 0, 0)) draw = ImageDraw.Draw(watermark) image = Image.open('chcsay.jpg') if drawTextInBox(text, [795, 140], [915, 725], draw) == False: return False, False mask = ImageEnhance.Brightness(watermark).enhance(0.2) image.paste(watermark, (0, 0), mask) data = io.BytesIO() image.save(data, format='JPEG', quality=85) data = data.getvalue() thumb = ImageOps.fit(image, [960, 540], Image.ANTIALIAS) thumbnail = io.BytesIO() thumb.save(thumbnail, format='JPEG', quality=85) thumbnail = thumbnail.getvalue() media = MediaWarehouse.create(sourceType="CHCSAY_1", mainDescription=text, data=data, thumbnail=thumbnail, tags=['chcsay', 'chcsay_1'], extension='jpg') url = MediaWarehouse.convertURL(media['id']) thumbnailURL = MediaWarehouse.convertThumbnailURL(media['id']) return url, thumbnailURL
async def getScrewSay3(text): media = MediaWarehouse.get(sourceType="SCREWSAY_3", mainDescription=text) if media is not None: url = MediaWarehouse.convertURL(media['id']) thumbnailURL = MediaWarehouse.convertThumbnailURL(media['id']) return url, thumbnailURL watermark = Image.new('RGBA', (3024, 4032), (0, 0, 0, 0)) draw = ImageDraw.Draw(watermark) image = Image.open('screwsay3.jpg') if drawTextInBox(text, [200, 150], [1300, 1400], draw, fontsize=320, color=(0, 0, 0, 200), weight='black') == False: return False, False mask = ImageEnhance.Brightness(watermark).enhance(0.2) image.paste(watermark, (0, 0), mask) data = io.BytesIO() ImageOps.fit(image, [1512, 2016], Image.ANTIALIAS).save(data, format='JPEG', quality=85) data = data.getvalue() thumb = ImageOps.fit(image, [756, 1008], Image.ANTIALIAS) thumbnail = io.BytesIO() thumb.save(thumbnail, format='JPEG', quality=85) thumbnail = thumbnail.getvalue() media = MediaWarehouse.create(sourceType="SCREWSAY_3", mainDescription=text, data=data, thumbnail=thumbnail, tags=['screwsay', 'screwsay_3'], extension='jpg') url = MediaWarehouse.convertURL(media['id']) thumbnailURL = MediaWarehouse.convertThumbnailURL(media['id']) return url, thumbnailURL
async def getScrewSay2(text): media = MediaWarehouse.get(sourceType="SCREWSAY_2", mainDescription=text) if media is not None: url = MediaWarehouse.convertURL(media['id']) thumbnailURL = MediaWarehouse.convertThumbnailURL(media['id']) return url, thumbnailURL FONTSIZE = 288 watermark = Image.new('RGBA', (1920, 1080), (0, 0, 0, 0)) draw = ImageDraw.Draw(watermark) image = Image.open('screwsay2.jpg') if drawTextInBox(text, [0, 0], [807, 784], draw, fontsize=256, color=(255, 255, 255, 200), weight='black') == False: return False, False mask = ImageEnhance.Brightness(watermark).enhance(0.2) image.paste(watermark, (0, 0), mask) data = io.BytesIO() image.save(data, format='JPEG', quality=85) data = data.getvalue() thumb = ImageOps.fit(image, [960, 540], Image.ANTIALIAS) thumbnail = io.BytesIO() thumb.save(thumbnail, format='JPEG', quality=85) thumbnail = thumbnail.getvalue() media = MediaWarehouse.create(sourceType="SCREWSAY_2", mainDescription=text, data=data, thumbnail=thumbnail, tags=['screwsay', 'screwsay_2'], extension='jpg') url = MediaWarehouse.convertURL(media['id']) thumbnailURL = MediaWarehouse.convertThumbnailURL(media['id']) return url, thumbnailURL
async def getHimawariSay2(text): media = MediaWarehouse.get(sourceType="HIMAWARISAY_ㄉ", mainDescription=text) if media is not None: url = MediaWarehouse.convertURL(media['id']) thumbnailURL = MediaWarehouse.convertThumbnailURL(media['id']) return url, thumbnailURL watermark = Image.new('RGBA', (1500, 1500), (0, 0, 0, 0)) draw = ImageDraw.Draw(watermark) image = Image.open('himawarisay2.jpg') if drawTextInBox(text, [225, 207], [639, 426], draw, fontsize=128, color=(0, 0, 0, 255)) == False: return False, False mask = ImageEnhance.Brightness(watermark).enhance(0.2) image.paste(watermark, (0, 0), mask) data = io.BytesIO() image.save(data, format='JPEG', quality=85) data = data.getvalue() thumb = ImageOps.fit(image, [750, 750], Image.ANTIALIAS) thumbnail = io.BytesIO() thumb.save(thumbnail, format='JPEG', quality=85) thumbnail = thumbnail.getvalue() media = MediaWarehouse.create(sourceType="HIMAWARISAY_2", mainDescription=text, data=data, thumbnail=thumbnail, tags=['himawarisay', 'himawarisay_2'], extension='jpg') url = MediaWarehouse.convertURL(media['id']) thumbnailURL = MediaWarehouse.convertThumbnailURL(media['id']) return url, thumbnailURL
async def getCatleeSay(text): media = MediaWarehouse.get(sourceType="CATLEESAY_1", mainDescription=text) if media is not None: url = MediaWarehouse.convertURL(media['id']) thumbnailURL = MediaWarehouse.convertThumbnailURL(media['id']) return url, thumbnailURL watermark = Image.new('RGBA', (960, 1706), (0, 0, 0, 0)) draw = ImageDraw.Draw(watermark) image = Image.open('catleeSay.jpg') if drawTextInBox(text, [0, 540], [960, 1166], draw, fontsize=512, color=(0, 0, 0, 255), weight='black') == False: return False, False mask = ImageEnhance.Brightness(watermark).enhance(0) image.paste(watermark, (0, 0), mask) thumb = ImageOps.fit(image, [240, 429], Image.ANTIALIAS) thumbnail = io.BytesIO() thumb.save(thumbnail, format='JPEG', quality=85) thumbnail = thumbnail.getvalue() data = io.BytesIO() thumb.save(data, format='JPEG', quality=85) data = data.getvalue() media = MediaWarehouse.create(sourceType="CATLEESAY_1", mainDescription=text, data=data, thumbnail=thumbnail, tags=['catleesay', 'catleesay_1'], extension='jpg') url = MediaWarehouse.convertURL(media['id']) thumbnailURL = MediaWarehouse.convertThumbnailURL(media['id']) return url, thumbnailURL
async def search_image(keyword): limit = datetime.datetime.now() - datetime.timedelta(0, EXPIRE_LIMIT) bufferedImg = MediaWarehouse.get(sourceType="GOOGLE", mainDescription=keyword, lastHit=limit, updateHit=True) if bufferedImg is None: res = googleimagesdownload() rawimg, url = await res.download_to_bytes_async({ "keywords": keyword, 'limit': 1 }) MAX_THUMB_SIZE = 512 image = Image.open(io.BytesIO(rawimg)) width, height = image.size max_border = max(width, height) scale_factor = MAX_THUMB_SIZE / max_border if max_border > MAX_THUMB_SIZE else 1 image = ImageOps.fit( image, [int(width * scale_factor), int(height * scale_factor)], Image.ANTIALIAS) image = image.convert("RGB") dataBuffer = io.BytesIO() image.save(dataBuffer, format='JPEG', quality=85) additionalData = json.dumps({ "width": image.size[0], "height": image.size[1], }) bufferedImg = MediaWarehouse.create(sourceType="GOOGLE", extension="jpg", data=dataBuffer.getvalue(), mainDescription=keyword, thumbnail=dataBuffer.getvalue(), additionalData=additionalData, source=url) additionalData = json.loads(bufferedImg['additionalData']) return bufferedImg['source'], MediaWarehouse.convertURL( bufferedImg['id']), additionalData['height'], additionalData['width']
async def getPayChanSay(text): media = MediaWarehouse.get(sourceType="PAYCHANSAY_1", mainDescription=text) if media is not None: url = MediaWarehouse.convertURL(media['id']) thumbnailURL = MediaWarehouse.convertThumbnailURL(media['id']) return url, thumbnailURL watermark = Image.new('RGBA', (1300, 700), (0, 0, 0, 0)) draw = ImageDraw.Draw(watermark) image = Image.open('paychansay.jpg') if drawTextInBox(text, [0, 0], [1300, 700], draw, fontsize=512, color=(255, 255, 255, 255), weight='serif_black') == False: return False, False coeffs = find_coeffs( [[1341, 2285], [2369, 2061], [2369, 2761], [1341, 3013]], [(0, 0), (1300, 0), (1300, 700), (0, 700)]) _watermark = watermark.transform((4032, 3024), Image.PERSPECTIVE, coeffs, Image.BILINEAR) mask = ImageEnhance.Brightness(_watermark).enhance(0.2) image.paste(_watermark, (0, 0), mask) data = io.BytesIO() image.save(data, format='JPEG', quality=85) data = data.getvalue() thumb = ImageOps.fit(image, [1008, 756], Image.ANTIALIAS) thumbnail = io.BytesIO() thumb.save(thumbnail, format='JPEG', quality=85) thumbnail = thumbnail.getvalue() media = MediaWarehouse.create(sourceType="PAYCHANSAY_1", mainDescription=text, data=data, thumbnail=thumbnail, tags=['paychansay', 'paychansay_1'], extension='jpg') url = MediaWarehouse.convertURL(media['id']) thumbnailURL = MediaWarehouse.convertThumbnailURL(media['id']) return url, thumbnailURL
async def getHimawariSay3(text): media = MediaWarehouse.get(sourceType="HIMAWARISAY_3", mainDescription=text) if media is not None: url = MediaWarehouse.convertURL(media['id']) thumbnailURL = MediaWarehouse.convertThumbnailURL(media['id']) return url, thumbnailURL watermark = Image.new('RGBA', (3941, 2955), (0, 0, 0, 0)) draw = ImageDraw.Draw(watermark) image = Image.open('himawarisay3.jpg') if drawTextInBox(text, [2029, 1705], [1700, 1100], draw, fontsize=1024, color=(0, 0, 0, 200), weight='black') == False: return False, False if drawTextInBox(text, [2009, 1685], [1700, 1100], draw, fontsize=1024, color=(255, 255, 255, 255), weight='black') == False: return False, False mask = ImageEnhance.Brightness(watermark).enhance(0.2) image.paste(watermark, (0, 0), mask) data = io.BytesIO() image.save(data, format='JPEG', quality=85) data = data.getvalue() thumb = ImageOps.fit(image, [985, 738], Image.ANTIALIAS) thumbnail = io.BytesIO() thumb.save(thumbnail, format='JPEG', quality=85) thumbnail = thumbnail.getvalue() media = MediaWarehouse.create(sourceType="HIMAWARISAY_3", mainDescription=text, data=data, thumbnail=thumbnail, tags=['himawarisay', 'himawarisay_3'], extension='jpg') url = MediaWarehouse.convertURL(media['id']) thumbnailURL = MediaWarehouse.convertThumbnailURL(media['id']) return url, thumbnailURL
async def getScrewSay7(text): media = MediaWarehouse.get(sourceType="SCREWSAY_7", mainDescription=text) if media is not None: url = MediaWarehouse.convertURL(media['id']) thumbnailURL = MediaWarehouse.convertThumbnailURL(media['id']) return url, thumbnailURL watermark = Image.new('RGBA', (640, 779), (0, 0, 0, 0)) draw = ImageDraw.Draw(watermark) image = Image.open('screwsay7.jpg') coeffs = find_coeffs([(4, 0), (640, 104), (636, 779), (0, 640)], [(0, 0), (615, 0), (615, 625), (0, 625)]) if drawTextInBox(text, [0, 0], [615, 625], draw, fontsize=160, color=(0, 0, 0, 200), weight='serif', vertical=True) == False: return False, False watermark = watermark.transform((1000, 1000), Image.PERSPECTIVE, coeffs, Image.BICUBIC) mask = ImageEnhance.Brightness(watermark).enhance(0.2) image.paste(watermark, (1809, 2265), mask) data = io.BytesIO() ImageOps.fit(image, [2016, 1512], Image.ANTIALIAS).save(data, format='JPEG', quality=85) data = data.getvalue() thumb = ImageOps.fit(image, [1008, 756], Image.ANTIALIAS) thumbnail = io.BytesIO() thumb.save(thumbnail, format='JPEG', quality=85) thumbnail = thumbnail.getvalue() media = MediaWarehouse.create(sourceType="SCREWSAY_7", mainDescription=text, data=data, thumbnail=thumbnail, tags=['screwsay', 'screwsay_7'], extension='jpg') url = MediaWarehouse.convertURL(media['id']) thumbnailURL = MediaWarehouse.convertThumbnailURL(media['id']) return url, thumbnailURL
async def getLouisSay(text): media = MediaWarehouse.get(sourceType="LOUISSAY_1", mainDescription=text) if media is not None: url = MediaWarehouse.convertURL(media['id']) thumbnailURL = MediaWarehouse.convertThumbnailURL(media['id']) return url, thumbnailURL watermark = Image.new('RGBA', (1477, 1110), (255, 255, 255, 0)) draw = ImageDraw.Draw(watermark) image = Image.open('louissay.jpg') if drawTextInBox(text, [89, 3], [700, 698], draw, fontsize=512, color=(255, 255, 255, 255), weight='black') == False: return False, False if drawTextInBox(text, [86, 0], [700, 698], draw, fontsize=512, color=(245, 209, 187, 255), weight='black') == False: return False, False mask = ImageEnhance.Brightness(watermark).enhance(0) image.paste(watermark, (0, 0), mask) data = io.BytesIO() image.save(data, format='JPEG', quality=85) data = data.getvalue() thumb = ImageOps.fit(image, [738, 555], Image.ANTIALIAS) thumbnail = io.BytesIO() thumb.save(thumbnail, format='JPEG', quality=85) thumbnail = thumbnail.getvalue() media = MediaWarehouse.create(sourceType="LOUISSAY_1", mainDescription=text, data=data, thumbnail=thumbnail, tags=['louissay', 'louissay_1'], extension='jpg') url = MediaWarehouse.convertURL(media['id']) thumbnailURL = MediaWarehouse.convertThumbnailURL(media['id']) return url, thumbnailURL
async def getWineSwordGodSay(text): media = MediaWarehouse.get(sourceType="WINESWORDGODSAY_1", mainDescription=text) if media is not None: url = MediaWarehouse.convertURL(media['id']) thumbnailURL = MediaWarehouse.convertThumbnailURL(media['id']) return url, thumbnailURL watermark = Image.new('RGBA', (4032, 3024), (0, 0, 0, 0)) draw = ImageDraw.Draw(watermark) image = Image.open('wineswordgodsay.jpg') if drawTextInBox(text, [2025, 0], [2007, 3024], draw, fontsize=512, color=(255, 255, 255, 200), weight='black') == False: return False, False mask = ImageEnhance.Brightness(watermark).enhance(0.2) image.paste(watermark, (0, 0), mask) data = io.BytesIO() image.save(data, format='JPEG', quality=85) data = data.getvalue() thumb = ImageOps.fit(image, [1008, 756], Image.ANTIALIAS) thumbnail = io.BytesIO() thumb.save(thumbnail, format='JPEG', quality=85) thumbnail = thumbnail.getvalue() media = MediaWarehouse.create( sourceType="WINESWORDGODSAY_1", mainDescription=text, data=data, thumbnail=thumbnail, tags=['wineswordgodsay', 'windswordgodsay_1'], extension='jpg') url = MediaWarehouse.convertURL(media['id']) thumbnailURL = MediaWarehouse.convertThumbnailURL(media['id']) return url, thumbnailURL
async def getFinance(basePath): companys = [ ("TWD=X", "USD/TWD"), ("TWDJPY=X", "TWD/JPY"), ("BTC-USD", "Bitcoin USD"), ("ETH-USD", "Ethereum USD"), ("AAPL", "Apple Inc."), ("GOOG", "Alphabet Inc."), ("FB", "Facebook, Inc."), ("AMZN", "Amazon.com, Inc."), ("TSLA", "Tesla, Inc."), ("UBER", "Uber Technologies, Inc."), ("ADBE", "Adobe Inc."), ("NVDA", "NVIDIA Corporation"), ("AMD", "Advanced Micro Devices, Inc."), ("INTC", "Intel Corporation"), ("QCOM", "QUALCOMM Incorporated"), ("TXN", "Texas Instruments Incorporated"), ("CSCO", "Cisco Systems, Inc."), ("ORCL", "Oracle Corporation"), ("IBM", "International Business Machines Corporation"), ("HPQ", "HP Inc."), ("NOK", "Nokia Corporation"), ("EA", "Electronic Arts Inc."), ("ATVI", "Activision Blizzard, Inc."), ("F", "Ford Motor Company"), ("GM", "General Motors Company"), ("MSFT", "Microsoft Corporation"), ("2330.TW", "Taiwan Semiconductor Manufacturing Company Limited "), ("2303.TW", "United Microelectronics Corporation"), ("2357.TW", "ASUSTeK Computer Inc."), ("2388.TW", "VIA Technologies, Inc."), ("2382.TW", "Quanta Computer Inc."), ("2409.TW", "AU Optronics Corp."), ("2454.TW", "MediaTek Inc."), ("3481.TW", "Innolux Corporation"), ("2317.TW", "Hon Hai Precision Industry Co., Ltd."), ("2412.TW", "Chunghwa Telecom Co., Ltd."), ("2002.TW", "China Steel Corporation"), ("1301.TW", "Formosa Plastics Corporation"), ("7974.T", "Nintendo Co., Ltd."), ("7203.T", "Toyota Motor Corporation"), ("7267.T", "Honda Motor Co., Ltd."), ("7951.T", "Yamaha Corporation"), ("7269.T", "Suzuki Motor Corporation"), ("7270.T", "Subaru Corporation"), ("2502.T", "Asahi Group Holdings, Ltd."), ("2501.T", "Sapporo Holdings Limited"), ("2587.T", "Suntory Beverage & Food Limited"), ("6758.T", "Sony Corporation"), ("BMW.DE", "Bayerische Motoren Werke Aktiengesellschaft"), ("DAI.DE", "Daimler AG") ] company, companyName = random.choice(companys) #mpl.style.use('default') _ticker = yfinance.Ticker(company) history = _ticker.history('1mo') currency = "" try: currency = _ticker.info['currency'] except: pass lastOpen = history.Open[-1] lastClose = history.Close[-1] ohlc_data = [] for line in history.iterrows(): ohlc_data.append((dates.date2num(line[0]), np.float64(line[1].Open), np.float64(line[1].High), np.float64(line[1].Low), np.float64(line[1].Close))) fig, ax1 = plt.subplots() candlestick_ohlc(ax1, ohlc_data, width=0.5, colorup='g', colordown='r', alpha=0.8) ax1.xaxis.set_major_formatter(dates.DateFormatter('%Y/%m/%d')) ax1.xaxis.set_major_locator(ticker.MaxNLocator(4)) plt.xticks(rotation=30) plt.grid() plt.tight_layout() filename = "{}_{}.png".format(company, time.strftime("%Y_%m_%d")) data = io.BytesIO() plt.savefig(data, format='png') data = data.getvalue() url = MediaWarehouse.convertURL( MediaWarehouse.create( extension='png', data=data, thumbnail=data, sourceType="FINANCE", source="https://finance.yahoo.com/quote/{}".format(company), mainDescription="{} - {}".format(companyName, datetime.datetime.now()), additionalData=json.dumps( { 'company': company, 'companyName': companyName, 'lastOpen': lastOpen, "lastClose": lastClose, "currency": currency }, ensure_ascii=False))['id']) plt.close() return url, company, companyName, lastOpen, lastClose, currency
async def randomWithType(sourceType, id=None): try: convs = { "MIKU": {"tags": ["初音ミク"], "tagOr": True}, "ERK": {"tags": ["裸足裏", "初音ミク"], "tagOr": False}, "YUGIOH_WAKE": {"tags": ["滝本ひふみ"], "tagOr": True}, "GANBARU": {"tags": ["今日も一日がんばるぞい!"], "tagOr": True}, "LOLI": {"tags": ["ロリ"], "tagOr": True}, "TOMGIRL": {"tags": ["男の娘"], "tagOr": True}, "REDIVE": {"tags": ["プリンセスコネクト!Re:Dive"], "tagOr": True}, "CHC": {"tags": ["GUMI", "ひだまりスケッチ", "きんいろモザイク", "NEWGAME!", "ご注文はうさぎですか?", "ゆるキャン△", "まちカドまぞく", "ブレンド・S", "ハナヤマタ", "GA芸術科アートデザインクラス", "けいおん!", "がっこうぐらし!", "Aチャンネル", "キルミーベイベー", "ゆゆ式"], "tagOr": True}, "MEGUMIN": {"tags": ["めぐみん", "このすば", "この素晴らしい世界に祝福を!"], "tagOr": True}, "YOSHIMARU": {"tags": ["よしまる", "国木田花丸", "津島善子"], "tagOr": True}, "KG": {"tags": ["アイカツ!", "アイカツ", "プリキュア", "プリパラ"], "tagOr": True}, "YURI": {"tags": ["百合"], "tagOr": True}, "RAIL": {"tags": ["電車", "鉄道"], "tagOr": True}, } if id is None: conv = convs[sourceType] media = MediaWarehouse.getMetadata(random=True, tags=conv["tags"], tagOr=conv["tagOr"]) return redirect("https://wakeupscrew.catlee.se/{}/{}".format(sourceType, media['id']), code=302) else: id = str(UUID(id)) media = MediaWarehouse.getMetadata(id=id) url = MediaWarehouse.convertURL(media['id']) thumb = MediaWarehouse.convertThumbnailURL(media['id']) thumbRetina = MediaWarehouse.convertThumbnailRetinaURL(media['id']) sourceTypes = list(reversed([ ["MIKU", "螺絲醒醒"], ["ERK", "螺絲矮額"], ["GANBARU", "ZOI"], ["YUGIOH_WAKE", "遊戲亡起床尿尿"], ["LOLI", "鱻鱻醒醒"], ["CHC", "CHC醒醒"], ["REDIVE", "市場醒醒"], ["MEGUMIN", "EXPLOSION"], ["YOSHIMARU", "阿部醒醒"], ["KG", "KG醒醒"], ["YURI", "真香"], ["RAIL", "車車"], ])) sourceTypeConv = { t[0]: t[1] for t in sourceTypes} if sourceType in [t[0] for t in sourceTypes]: pixiv = json.loads(media['additionalData'])['pixiv_v2'] now = datetime.datetime.now().timestamp() return await render_template("pixiv.html", pixiv=pixiv, url=url, thumb=thumb, thumbRetina=thumbRetina, source=media['source'], sourceType=sourceType, now=now, sourceTypes=sourceTypes, sourceTypeConv=sourceTypeConv) else: return redirect(url, code=302) except Exception as e: logging.exception(e) abort(404)
async def random(): url = MediaWarehouse.convertURL(MediaWarehouse.get(random=True, lastHit=datetime.datetime.now() - datetime.timedelta(days=30*6))['id']) return redirect(url, code=302)
async def findTags(keyword): tags = MediaWarehouse.findTags(keyword) return Response(json.dumps(tags, ensure_ascii=False), mimetype='application/json')
async def listTags(skip=0, num=50): popularTags, _ = MediaWarehouse.popularTags(num, skip=skip) return Response(json.dumps(popularTags, ensure_ascii=False), mimetype='application/json')
async def randomWithTag(tags): media = MediaWarehouse.getMetadata(random=True, tags=tags.split(' ')if len(tags)>0 else None) return redirect("https://wakeupscrew.catlee.se/tag/{}/{}".format(urllib.parse.quote(tags), media['id']), code=302)
async def index(): randomTag = MediaWarehouse.randomTag() return await render_template("pixiv_search.html", randomTag=randomTag)
)""" '''migrate( migrator.add_column('media', 'disabled', BooleanField(default=False)) )''' #print(MediaWarehouse.listTags(MediaWarehouse.get(tags=['初音ミク', 'Fate/GrandOrder'], random=True, tagOr=True)['id'])) '''tags = ['下着', 'Fate/GrandOrder'] idListPerTag = [] for tag in tags: _tags = Tagv2.select().where(Tagv2.name.contains(tag)) idListPerTag.append(Media.id << MediaToTag.select(MediaToTag.media_id).where(MediaToTag.tag << _tags)) print(idListPerTag) idExpression = reduce(lambda x,y:x | y, idListPerTag) print(Media.select().where(idExpression).sql())''' #db.create_tables([Description]) '''for media in tqdm(Media.select(Media.id, Media.additionalData).where(Media.sourceType == "PIXIV").iterator(), total=Media.select(Media.id).where(Media.sourceType == "PIXIV").count()): if media.additionalData: #and not Description.select().where(Description.id == media.id).exists(): try: additionalData = json.loads(media.additionalData)["pixiv_v2"] text = "{} {} {} {}".format(additionalData["title"], additionalData["caption"], " ".join(additionalData["tags"]), additionalData["user"]["name"]) #Description.get_or_create(id = media.id, text = text) Description.update({Description.text: text}).where(Description.id == media.id) except Exception as e: print(e)''' #print(MediaWarehouse.popularTags()) now = datetime.datetime.now() result = MediaWarehouse.searchMetadata(tags=["初音ミク", "裸足"], random=True) print(result) print(result[0]['id']) print(Description.select().where( Description.id == result[0]['id']).get().text) print(datetime.datetime.now() - now)