Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
DevAVR authored Feb 28, 2021
0 parents commit 1e05f21
Show file tree
Hide file tree
Showing 16 changed files with 667 additions and 0 deletions.
1 change: 1 addition & 0 deletions Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
worker: python3 main.py
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Streams Extractor Bot



45 changes: 45 additions & 0 deletions app.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
{
"name": "Subtitle Translate Bot",
"description": "A Bot that can Translate Subtitles into 100+ different Languages using Google Cloud Translate API",
"logo": "https://telegra.ph/file/71aaa621508cd696ab538.jpg",
"keywords": [
"Subtitle",
"Translator",
"Google Translate API",
"Telegram Bot",
"TroJanzHEX"
],
"website": "https://TroJanzHEX.me",
"repository": "https://github.com/TroJanzHEX/Subtitle-Translator",
"success_url": "https://telegram.dog/TroJanzHEX",
"env": {
"TG_BOT_TOKEN": {
"description": "You Telegram Bot Token from @BotFather",
"value": ""
},
"API_HASH": {
"description": "Your API Hash from my.telegram.org",
"value": ""
},
"WEBHOOK": {
"description": "Set this Value to 'ANYTHING'. Don't Change it.",
"value": "ANYTHING"
},
"APP_ID": {
"description": "Your APP ID from my.telegram.org",
"value": ""
}
},
"addons": [],
"buildpacks": [
{
"url": "heroku/python"
}
],
"formation": {
"worker": {
"quantity": 1,
"size": "free"
}
}
}
12 changes: 12 additions & 0 deletions config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# By @TroJanzHEX


import os

class Config(object):
BOT_TOKEN = os.environ.get("BOT_TOKEN", "")

APP_ID = int(os.environ.get("APP_ID", 12345))

API_HASH = os.environ.get("API_HASH", "")

82 changes: 82 additions & 0 deletions helpers/download.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import os
import pyrogram
import time
import json

from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from helpers.progress import progress_func
from helpers.tools import execute, clean_up

DATA = {}

async def download_file(client, message):
media = message.reply_to_message
if media.empty:
await message.reply_text('Why did you delete that 😕', True)
return

msg = await client.send_message(
chat_id=message.chat.id,
text="**Downloading...**",
reply_markup=InlineKeyboardMarkup(
[[InlineKeyboardButton(text="Progress", callback_data="progress_msg")]]),
reply_to_message_id=media.message_id
)
filetype = media.document or media.video

c_time = time.time()

download_location = await client.download_media(
message=media,
progress=progress_func,
progress_args=(
"**Downloading...**",
msg,
c_time,
client
)
)

await msg.edit_text("```Processing...```")

output = await execute(f"ffprobe -hide_banner -show_streams -print_format json '{download_location}'")

if not output:
await clean_up(download_location)
await msg.edit_text("```Some Error Occured while Fetching Details...```")
return

details = json.loads(output[0])
buttons = []
DATA[f"{message.chat.id}-{msg.message_id}"] = {}
for stream in details["streams"]:
mapping = stream["index"]
stream_name = stream["codec_name"]
stream_type = stream["codec_type"]
if stream_type in ("audio", "subtitle"):
pass
else:
continue
try:
lang = stream["tags"]["language"]
except:
lang = mapping

DATA[f"{message.chat.id}-{msg.message_id}"][int(mapping)] = {
"map" : mapping,
"name" : stream_name,
"type" : stream_type,
"lang" : lang,
"location" : download_location
}
buttons.append([InlineKeyboardButton(f"{stream_type.upper()} - {str(lang).upper()}", f"{stream_type}_{mapping}_{message.chat.id}-{msg.message_id}")])

buttons.append([InlineKeyboardButton("CANCEL",f"cancel_{mapping}_{message.chat.id}-{msg.message_id}")])

await msg.edit_text(
"**Select the Stream to be Extracted...**",
reply_markup=InlineKeyboardMarkup(buttons)
)



45 changes: 45 additions & 0 deletions helpers/ffmpeg.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
from helpers.tools import execute, clean_up
from helpers.upload import upload_audio, upload_subtitle

async def extract_audio(client, message, data):
await message.edit_text("```Extracting Stream...```")

dwld_loc = data['location']
out_loc = data['location'] + ".mp3"

if data['name'] == "mp3":
out, err, rcode, pid = await execute(f"ffmpeg -i '{dwld_loc}' -map 0:{data['map']} -c copy '{out_loc}' -y")
if rcode != 0:
await message.edit_text("**Error Occured.See Logs for more info.**")
print(err)
await clean_up(dwld_loc, out_loc)
return
else:
out, err, rcode, pid = await execute(f"ffmpeg -i '{dwld_loc}' -map 0:{data['map']} '{out_loc}' -y")
if rcode != 0:
await message.edit_text("**Error Occured.See Logs for more info.**")
print(err)
await clean_up(dwld_loc, out_loc)
return

await clean_up(dwld_loc)
await upload_audio(client, message, out_loc)



async def extract_subtitle(client, message, data):
await message.edit_text("```Extracting Stream...```")

dwld_loc = data['location']
out_loc = data['location'] + ".srt"

out, err, rcode, pid = await execute(f"ffmpeg -i '{dwld_loc}' -map 0:{data['map']} -c copy '{out_loc}' -y")
if rcode != 0:
await message.edit_text("**Error Occured.See Logs for more info.**")
print(err)
await clean_up(dwld_loc, out_loc)
return

await clean_up(dwld_loc)
await upload_subtitle(client, message, out_loc)

65 changes: 65 additions & 0 deletions helpers/progress.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import math
import os
import time
import asyncio

if bool(os.environ.get("WEBHOOK", False)):
from sample_config import Config
else:
from config import Config

PRGRS = {}


async def progress_func(
current,
total,
ud_type,
message,
start,
client
):
now = time.time()
diff = now - start
if round(diff % 5.00) == 0 or current == total:
percentage = current * 100 / total
speed = current / diff
elapsed_time = round(diff) * 1000
time_to_completion = round((total - current) / speed) * 1000
estimated_total_time = elapsed_time + time_to_completion

elapsed_time = TimeFormatter(milliseconds=elapsed_time)
estimated_total_time = TimeFormatter(milliseconds=estimated_total_time)

PRGRS[f"{message.chat.id}_{message.message_id}"] = {
"current": humanbytes(current),
"total": humanbytes(total),
"speed": humanbytes(speed),
"progress": percentage,
"eta": elapsed_time
}


def humanbytes(size):
if not size:
return ""
power = 2**10
n = 0
Dic_powerN = {0: ' ', 1: 'K', 2: 'M', 3: 'G', 4: 'T'}
while size > power:
size /= power
n += 1
return str(round(size, 2)) + " " + Dic_powerN[n] + 'B'


def TimeFormatter(milliseconds: int) -> str:
seconds, milliseconds = divmod(int(milliseconds), 1000)
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
tmp = ((str(days) + "d, ") if days else "") + \
((str(hours) + "h, ") if hours else "") + \
((str(minutes) + "m, ") if minutes else "") + \
((str(seconds) + "s, ") if seconds else "") + \
((str(milliseconds) + "ms, ") if milliseconds else "")
return tmp[:-2]
26 changes: 26 additions & 0 deletions helpers/tools.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import os
import shlex
import asyncio
from typing import Tuple, List, Optional


async def execute(cmnd: str) -> Tuple[str, str, int, int]:
cmnds = shlex.split(cmnd)
process = await asyncio.create_subprocess_exec(*cmnds,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)
stdout, stderr = await process.communicate()
return (stdout.decode('utf-8', 'replace').strip(),
stderr.decode('utf-8', 'replace').strip(),
process.returncode,
process.pid)

async def clean_up(input1, input2=None):
try:
os.remove(input1)
except:
pass
try:
os.remove(input2)
except:
pass
86 changes: 86 additions & 0 deletions helpers/upload.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import time
from hachoir.metadata import extractMetadata
from hachoir.parser import createParser
from helpers.progress import progress_func
from helpers.tools import clean_up
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton

async def upload_audio(client, message, file_loc):

msg = await message.edit_text(
text="**Uploading...**",
reply_markup=InlineKeyboardMarkup(
[[InlineKeyboardButton(text="Progress", callback_data="progress_msg")]])
)

title = None
artist = None
thumb = None
duration = 0

metadata = extractMetadata(createParser(file_loc))
if metadata and metadata.has("title"):
title = metadata.get("title")
if metadata and metadata.has("artist"):
artist = metadata.get("artist")
if metadata and metadata.has("duration"):
duration = metadata.get("duration").seconds

c_time = time.time()

try:
await client.send_audio(
chat_id=message.chat.id,
audio=file_loc,
thumb=thumb,
caption="**@TroJanzHEX**",
title=title,
performer=artist,
duration=duration,
progress=progress_func,
progress_args=(
"**Uploading...**",
msg,
c_time,
client
)
)
except Exception as e:
print(e)
await msg.edit_text("**Some Error Occurred. See Logs for More Info.**")
return

await msg.delete()
await clean_up(file_loc)


async def upload_subtitle(client, message, file_loc):

msg = await message.edit_text(
text="**Uploading...**",
reply_markup=InlineKeyboardMarkup(
[[InlineKeyboardButton(text="Progress", callback_data="progress_msg")]])
)

c_time = time.time()

try:
await client.send_document(
chat_id=message.chat.id,
document=file_loc,
caption="**@TroJanzHEX**",
progress=progress_func,
progress_args=(
"**Uploading...**",
msg,
c_time,
client
)
)
except Exception as e:
print(e)
await msg.edit_text("**Some Error Occurred. See Logs for More Info.**")
return

await msg.delete()
await clean_up(file_loc)
Loading

0 comments on commit 1e05f21

Please sign in to comment.