class File: is_video: Filter = Filter(lambda event: is_video(event.media)) is_image: Filter = Filter(lambda event: is_image(event.media)) is_gif: Filter = Filter(lambda event: is_gif(event.document)) is_audio: Filter = Filter(lambda event: is_audio(event.media)) # generated by extensions # Image extensions png: Filter = _FilterVar() jpeg: Filter = _FilterVar() webp: Filter = _FilterVar() gif: Filter = _FilterVar() bmp: Filter = _FilterVar() tga: Filter = _FilterVar() tiff: Filter = _FilterVar() psd: Filter = _FilterVar() # Video extensions mp4: Filter = _FilterVar() mov: Filter = _FilterVar() avi: Filter = _FilterVar() # Audio extensions mp2: Filter = _FilterVar() # a.k.a. ISO/IEC 13818-2 mp3: Filter = _FilterVar() m4a: Filter = _FilterVar() aac: Filter = _FilterVar() ogg: Filter = _FilterVar() flac: Filter = _FilterVar() # Win executable extension exe: Filter = _FilterVar()
async def handler(event): message_text = None text_in_image = None if event.message.media is not None: if is_image(event.message.media): await client.download_media(event.message.media, config["temp_path"] + 'temp.jpg') time.sleep(2) # Get HOCR output hocr = pytesseract.image_to_pdf_or_hocr(config["temp_path"] + 'temp.jpg', extension='hocr') soup = BeautifulSoup(hocr.decode('utf-8'), 'html.parser') elements = soup.find_all("span", class_="ocrx_word") text = '' for elm in elements: text += elm.text text_in_image = re.findall(r'[A-Z]{3}\s*/\s*[A-Z]{3}', text) if len(text_in_image) > 0: text_in_image = "Symbol: " + text_in_image[0].replace( '/', '').replace(" ", "") message_from_sender = parese_message(event.message.message) if message_from_sender is not None and text_in_image is not None: message_text = text_in_image + "\n" + message_from_sender elif text_in_image is None: message_text = message_from_sender elif message_from_sender is None: message_text = text_in_image await client.send_message(output_channel_entity, message_text)
async def areverse(e): media = e.media if not media: r = await e.get_reply_message() media = getattr(r, 'media', None) if not media: await e.edit('err \\\nMedia required') return ig = is_gif(media) or is_video(media) if not is_image(media) and not ig: await e.edit('err \\\nMedia must be an image or gif or video') return filename = 'file.jpg' if not ig and isinstance(media, MessageMediaDocument): attribs = media.document.attributes for i in attribs: if isinstance(i, DocumentAttributeFilename): filename = i.file_name break await e.edit('`Downloading image...`') content = await e.client.download_media(media, bytes, thumb=-1 if ig else None) await e.edit('`Searching for result...`') file = memory_file(filename, content) async with aiohttp.ClientSession() as session: url = 'https://trace.moe/api/search' async with session.post(url, data={'image': file}) as raw_resp0: resp0 = await raw_resp0.text() js0 = json.loads(resp0)['docs'] if not js0: await e.edit('err \\\nNo results found') return js0 = js0[0] text = f'<b>{html.escape(js0["title_romaji"])}' if js0['title_native']: text += f' ({html.escape(js0["title_native"])})' text += '</b>\n' if js0['episode']: text += f'<b>Episode:</b> {html.escape(str(js0["episode"]))}\n' percent = round(js0['similarity'] * 100, 2) text += f'<b>Similarity:</b> {percent}%\n' dt = pendulum.from_timestamp(js0['at']) text += f'<b>At:</b> {html.escape(dt.to_time_string())}' await e.edit(text, parse_mode='html') dt0 = pendulum.from_timestamp(js0['from']) dt1 = pendulum.from_timestamp(js0['to']) ctext = f'{html.escape(dt0.to_time_string())} - {html.escape(dt1.to_time_string())}' url = ('https://trace.moe/preview.php' f'?anilist_id={urlencode(str(js0["anilist_id"]))}' f'&file={urlencode(js0["filename"])}' f'&t={urlencode(str(js0["at"]))}' f'&token={urlencode(js0["tokenthumb"])}') async with session.get(url) as raw_resp1: file = memory_file('preview.mp4', await raw_resp1.read()) try: await e.reply(ctext, file=file, parse_mode='html') except FilePartsInvalidError: await e.reply('`Cannot send preview :/`')
async def whatanime(e): media = e.media if not media: r = await e.get_reply_message() media = getattr(r, "media", None) if not media: await edit_delete(e, "`Media required`") return ig = is_gif(media) or is_video(media) if not is_image(media) and not ig: await edit_delete(e, "`Media must be an image or gif or video`") return filename = "file.jpg" if not ig and isinstance(media, MessageMediaDocument): attribs = media.document.attributes for i in attribs: if isinstance(i, DocumentAttributeFilename): filename = i.file_name break xx = await edit_or_reply(e, "`Downloading image..`") content = await e.client.download_media(media, bytes, thumb=-1 if ig else None) await xx.edit("`Searching for result..`") file = memory_file(filename, content) async with aiohttp.ClientSession() as session: url = "https://api.trace.moe/search?anilistInfo" async with session.post(url, data={"image": file}) as raw_resp0: resp0 = await raw_resp0.json() js0 = resp0.get("result") if not js0: await xx.edit("`No results found.`") return js0 = js0[0] text = f'<b>{html.escape(js0["anilist"]["title"]["romaji"])}' if js0["anilist"]["title"]["native"]: text += f' ({html.escape(js0["anilist"]["title"]["native"])})' text += "</b>\n" if js0["episode"]: text += f'<b>Episode:</b> {html.escape(str(js0["episode"]))}\n' percent = round(js0["similarity"] * 100, 2) text += f"<b>Similarity:</b> {percent}%\n" at = re.findall(r"t=(.+)&", js0["video"])[0] dt = pendulum.from_timestamp(float(at)) text += f"<b>At:</b> {html.escape(dt.to_time_string())}" await e.edit(text, parse_mode="html") dt0 = pendulum.from_timestamp(js0["from"]) dt1 = pendulum.from_timestamp(js0["to"]) ctext = ( f"{html.escape(dt0.to_time_string())} - {html.escape(dt1.to_time_string())}" ) async with session.get(js0["video"]) as raw_resp1: file = memory_file("preview.mp4", await raw_resp1.read()) try: await xx.edit(ctext, file=file, parse_mode="html") except FilePartsInvalidError: await xx.edit("`Cannot send preview.`")
async def handle_callback(event): choice = event.data msg = await event.get_message() sender = await get_sender_info(event) message = await msg.get_reply_message() if choice == NORMAL: resize_func = normal_resize elif choice == SEAM_CARVING: resize_func = seam_carving_resize else: logger.warning(f'Get wrong resize func: {choice} from {sender!r}') return await event.edit('Request accepted, downloading...') with BytesIO() as in_f, BytesIO() as out_f: success = await client.download_media(message, file=in_f) await event.edit('File received, processing') if success is None: logger.info('Fail to download media') await event.edit('Fail to download media') return in_f.flush() in_f.seek(0) if not is_image(in_f): logger.debug("Media is not image") await event.edit('Media is not image') return in_f.seek(0) with ProcessPoolExecutor() as pool: new_img = await client.loop.run_in_executor( pool, resize_func, in_f) file_name, ext = splitext(get_media_filename(message.media)) out_f.name = f'Resized_{file_name}.png' is_success, im_buf_arr = cv2.imencode('.png', new_img) if not is_success: logger.debug("OpenCV can't transform img to bytes") return out_f.write(im_buf_arr.tobytes()) out_f.flush() out_f.seek(0) prompt = f'Sending Resized File:{out_f.name!r}' logger.debug(f'{prompt} to {sender!r}') await event.edit(text=prompt) await message.reply(file=out_f, force_document=True) await event.edit('Finished')
class File: """ Namespace for file extension filters. Usage: >>> from garnet.filters import File ... >>> @router.message(File.is_video & (File.mp4 | File.mov)) ... async def handle_video(event): pass >>> >>> @router.message(File.is_audio) ... async def handle_audio(): pass """ is_video: FE = Filter(lambda event: is_video(event.media)) is_image: FE = Filter(lambda event: is_image(event.media)) is_gif: FE = Filter(lambda event: is_gif(event.document)) is_audio: FE = Filter(lambda event: is_audio(event.media)) # generated by extensions # Image extensions png: FE = _FilterVar() jpeg: FE = _FilterVar() webp: FE = _FilterVar() gif: FE = _FilterVar() bmp: FE = _FilterVar() tga: FE = _FilterVar() tiff: FE = _FilterVar() psd: FE = _FilterVar() # Video extensions mp4: FE = _FilterVar() mov: FE = _FilterVar() avi: FE = _FilterVar() # Audio extensions mp2: FE = _FilterVar() # a.k.a. ISO/IEC 13818-2 mp3: FE = _FilterVar() m4a: FE = _FilterVar() aac: FE = _FilterVar() ogg: FE = _FilterVar() flac: FE = _FilterVar() # Win executable extension exe: FE = _FilterVar()
async def whatnime(e): media = e.media if not media: r = await e.get_reply_message() media = getattr(r, "media", None) if not media: await e.edit("`Media required`") return ig = is_gif(media) or is_video(media) if not is_image(media) and not ig: await e.edit("`Media must be an image or gif or video`") return filename = "file.jpg" if not ig and isinstance(media, MessageMediaDocument): attribs = media.document.attributes for i in attribs: if isinstance(i, DocumentAttributeFilename): filename = i.file_name break await e.edit("`Mencari Judul Anime...`") content = await e.client.download_media(media, bytes, thumb=-1 if ig else None) await e.edit("`Mencari Hasil..`") file = memory_file(filename, content) async with aiohttp.ClientSession() as session: url = "https://trace.moe/api/search" async with session.post(url, data={"image": file}) as raw_resp0: resp0 = await raw_resp0.text() js0 = json.loads(resp0)["docs"] if not js0: await e.edit("`No results found.`") return js0 = js0[0] text = f'<b>{html.escape(js0["title_romaji"])}' if js0["title_native"]: text += f' ({html.escape(js0["title_native"])})' text += "</b>\n" if js0["episode"]: text += f'<b>Episode:</b> {html.escape(str(js0["episode"]))}\n' percent = round(js0["similarity"] * 100, 2) text += f"<b>Similarity:</b> {percent}%\n" dt = pendulum.from_timestamp(js0["at"]) text += f"<b>At:</b> {html.escape(dt.to_time_string())}" await e.edit(text, parse_mode="html") dt0 = pendulum.from_timestamp(js0["from"]) dt1 = pendulum.from_timestamp(js0["to"]) ctext = ( f"{html.escape(dt0.to_time_string())} - {html.escape(dt1.to_time_string())}" ) url = ("https://trace.moe/preview.php" f'?anilist_id={urlencode(str(js0["anilist_id"]))}' f'&file={urlencode(js0["filename"])}' f'&t={urlencode(str(js0["at"]))}' f'&token={urlencode(js0["tokenthumb"])}') async with session.get(url) as raw_resp1: file = memory_file("preview.mp4", await raw_resp1.read()) try: await e.reply(ctext, file=file, parse_mode="html") except FilePartsInvalidError: await e.reply("`Cannot send preview.`")
async def whatanime(e): media = e.media if not media: r = await e.get_reply_message() media = getattr(r, "media", None) if not media: await e.edit("`Mídia necessária`") return ig = is_gif(media) or is_video(media) if not is_image(media) and not ig: await e.edit("`A mídia deve ser uma imagem ou gif ou vídeo`") return filename = "file.jpg" if not ig and isinstance(media, MessageMediaDocument): attribs = media.document.attributes for i in attribs: if isinstance(i, DocumentAttributeFilename): filename = i.file_name break await e.edit("`Baixando imagem..`") content = await e.client.download_media(media, bytes, thumb=-1 if ig else None) await e.edit("`Procurando resultados..`") file = memory_file(filename, content) async with aiohttp.ClientSession() as session: url = "https://trace.moe/api/search" async with session.post(url, data={"image": file}) as raw_resp0: resp0 = await raw_resp0.text() js0 = json.loads(resp0)["docs"] if not js0: await e.edit("`Nenhum resultado encontrado.`") return js0 = js0[0] text = f'<b>{html.escape(js0["title_romaji"])}' if js0["title_native"]: text += f' ({html.escape(js0["title_native"])})' text += "</b>\n" if js0["episode"]: text += f'<b>Episódio:</b> {html.escape(str(js0["episode"]))}\n' percent = round(js0["similarity"] * 100, 2) text += f"<b>Semelhança:</b> {percent}%\n" dt = pendulum.from_timestamp(js0["at"]) text += f"<b>Em:</b> {html.escape(dt.to_time_string())}" await e.edit(text, parse_mode="html") dt0 = pendulum.from_timestamp(js0["from"]) dt1 = pendulum.from_timestamp(js0["to"]) ctext = ( f"{html.escape(dt0.to_time_string())} - {html.escape(dt1.to_time_string())}" ) url = ("https://media.trace.moe/video/" f'{urlencode(str(js0["anilist_id"]))}' + "/" f'{urlencode(js0["filename"])}' f'?t={urlencode(str(js0["at"]))}' f'&token={urlencode(js0["tokenthumb"])}') async with session.get(url) as raw_resp1: file = memory_file("preview.mp4", await raw_resp1.read()) try: await e.reply(ctext, file=file, parse_mode="html") except FilePartsInvalidError: await e.reply("`Não foi possível enviar visualização.`")
async def whatanime(e): media = e.media if not media: r = await e.get_reply_message() media = getattr(r, "media", None) if not media: await e.edit("`Dibutuhkan media`") return ig = is_gif(media) or is_video(media) if not is_image(media) and not ig: await e.edit("`Media harus berupa gambar, gif atau video`") return filename = "file.jpg" if not ig and isinstance(media, MessageMediaDocument): attribs = media.document.attributes for i in attribs: if isinstance(i, DocumentAttributeFilename): filename = i.file_name break await e.edit("`Mengunduh gambar...`") content = await e.client.download_media(media, bytes, thumb=-1 if ig else None) await e.edit("`Mencari hasil...`") file = memory_file(filename, content) async with aiohttp.ClientSession() as session: url = "https://trace.moe/api/search" async with session.post(url, data={"image": file}) as raw_resp0: resp0 = await raw_resp0.text() js0 = json.loads(resp0)["docs"] if not js0: await e.edit("`Tidak ada hasil yang ditemukan.`") return js0 = js0[0] text = f'<b>{html.escape(js0["title_romaji"])}' if js0["title_native"]: text += f' ({html.escape(js0["title_native"])})' text += "</b>\n" if js0["episode"]: text += f'<b>Episode :</b> {html.escape(str(js0["episode"]))}\n' percent = round(js0["similarity"] * 100, 2) text += f"<b>Kesamaan :</b> {percent}%\n" dt = pendulum.from_timestamp(js0["at"]) text += f"<b>Di :</b> {html.escape(dt.to_time_string())}" await e.edit(text, parse_mode="html") dt0 = pendulum.from_timestamp(js0["from"]) dt1 = pendulum.from_timestamp(js0["to"]) ctext = ( f"{html.escape(dt0.to_time_string())} - {html.escape(dt1.to_time_string())}" ) url = ("https://media.trace.moe/video/" f'{urlencode(str(js0["anilist_id"]))}' + "/" f'{urlencode(js0["filename"])}' f'?t={urlencode(str(js0["at"]))}' f'&token={urlencode(js0["tokenthumb"])}') async with session.get(url) as raw_resp1: file = memory_file("preview.mp4", await raw_resp1.read()) try: await e.reply(ctext, file=file, parse_mode="html") except FilePartsInvalidError: await e.reply("`Tidak dapat mengirim pratinjau.`")