Skip to content

Commit

Permalink
proper splitting
Browse files Browse the repository at this point in the history
  • Loading branch information
Koushikphy committed Jun 19, 2022
1 parent cb310a0 commit 162a1b4
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 35 deletions.
3 changes: 2 additions & 1 deletion Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@ Take Photo/Audio/Video from webcam by remotely controlling it using a Telegram b
1. Download and install the `ffmpeg` library for video processing. The `ffmpeg` executable should be available in the path.
2. Start the bot with `pipenv run bot`
1. Available commands
1. `/photo` - Take photo
1. `/photo` - Take a temporary photo
2. `/audio` - Take audio
3. `/video` - Take video
4. `/photo_keep` - Take and keep photo
4. `/videoonly` - Take video without audio

**NOTE:**
Expand Down
23 changes: 11 additions & 12 deletions telegramBot.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ def cancel(self):


def deleteMessage(message, delay=0):
# delete a message, optionally define a delay for the delete
def tempDelete(message):
bot.delete_message(message.chat.id, message.message_id)
if delay: # dely non zero means delete some times later
Expand All @@ -49,7 +50,6 @@ def make_logger():
#Create the logger
logger = logging.getLogger('Tel')
logger.setLevel(logging.INFO)
# file = os.path.join(os.path.expanduser('~'), 'ADT.log' )
fh = logging.FileHandler("tel.log")
fh.setLevel(logging.INFO)
fh.setFormatter(logging.Formatter("[%(asctime)s] - %(message)s","%d-%m-%Y %I:%M:%S %p"))
Expand All @@ -62,6 +62,7 @@ def make_logger():


def checkRequest(message):
# check if the request is from a valid user, if not send a notification to admin
user = message.from_user

if user.id not in ALLOWED_USERS:
Expand Down Expand Up @@ -92,6 +93,7 @@ def send_photo2(message):


def takePhoto(message, toDelete=False):
# capture and send the photo, optionally delete after 5 second
user = message.from_user.id
if checkRequest(message):
return
Expand All @@ -115,6 +117,7 @@ def takePhoto(message, toDelete=False):

@bot.message_handler(commands='audio')
def send_audio(message):
# start audio recording
user = message.from_user.id
if checkRequest(message):
return
Expand Down Expand Up @@ -226,17 +229,8 @@ def callback_query(call):
terminate(user, videoRecorder, audioRecorder)




def terminate(user, *recorders):
for rec in recorders:
rec.terminate()
bot.send_message(user, "Recording terminated")
logger.info('Recording terminated')



def processAndUpload(user, file, act):
# process recording and send to user
logger.info(f"Recording finished: {os.path.basename(file)} ({act:.2f} sec) ({os.path.getsize(file)/1e6:.2f} MB)")
files = splitFilesInChunks(file, act, chunks=600)
nTxt = "The file will be split due to Telegram restrictions." if len(files)>1 else ""
Expand All @@ -247,7 +241,6 @@ def processAndUpload(user, file, act):
with open(file, 'rb') as f:
if file.endswith('mp4'):
bot.send_video(user, f)
# print(f)
else:
bot.send_audio(user, f)
except:
Expand All @@ -260,6 +253,12 @@ def processAndUpload(user, file, act):



def terminate(user, *recorders):
for rec in recorders:
rec.terminate()
bot.send_message(user, "Recording terminated")
logger.info('Recording terminated')




Expand Down
38 changes: 16 additions & 22 deletions utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,9 +202,6 @@ def finish(self):
fileName = getFileName('Video', 'mp4')
totalTime = self.closeCapture()
thisFPS = self.framescount / totalTime
# acT = self.fps*totalTime/thisFPS # actual time of the video after the rescaling FPS
# print(totalTime, acT, thisFPS, self.fps)
# subprocess.call(f"ffprobe.exe {self.tempFile}")
reFFMPEG(self.tempFile, thisFPS, fileName, self.fps)
return fileName, totalTime

Expand All @@ -214,7 +211,6 @@ def finishWithAudio(self, audioStream):
fileName = getFileName('Video', 'mp4')
totalTime = self.closeCapture()
thisFPS = self.framescount / totalTime
# acT = self.fps*totalTime/thisFPS # actual time of the video after the rescaling FPS
reMergeFFMPEG(self.tempFile, audioStream, thisFPS, self.fps, fileName)
return fileName, totalTime

Expand All @@ -223,59 +219,57 @@ def finishWithAudio(self, audioStream):

def reFFMPEG(iFile, iFPS, oFile, oFPS, crf=24):
# change fps of the video file, writes output to `ffmpeg.log`
ret = subprocess.call(f"ffmpeg -y -r {iFPS} -i {iFile} -r {oFPS} -vcodec libx265 -crf {crf} {oFile} >> ffmpeg.log 2>&1", shell=True)
ret = subprocess.call(f"ffmpeg -y -r {iFPS} -i {iFile} -r {oFPS} \
-vcodec libx265 -crf {crf} {oFile} >> ffmpeg.log 2>&1"
, shell=True)
if ret==0:
removeFile(iFile)


def mergeFFMPEG(videoStream, audioStream, videoOut):
# merge audio and video stream, writes output to `ffmpeg.log`
ret = subprocess.call( f"ffmpeg -ac 2 -y -channel_layout stereo -i {videoStream} -i {audioStream} \
{videoOut} >> ffmpeg.log 2>&1",
ret = subprocess.call(
f"ffmpeg -ac 2 -y -channel_layout stereo -i {videoStream} -i {audioStream} \
{videoOut} >> ffmpeg.log 2>&1",
shell=True)
if ret==0:
removeFile(videoStream, audioStream)


def wavTo_m4a(inFile,outFile):
# convert .wav to .m4a file
ret= subprocess.call(f"ffmpeg -i {inFile} {outFile} >> ffmpeg.log 2>&1", shell=True)
if ret==0:
removeFile(inFile)


def reMergeFFMPEG(videoStream, audioStream,iFPS,oFPS, videoOut,crf=24):
# change fps and attach the audio stream
ret = subprocess.call(
f"ffmpeg -ac 2 -y -channel_layout stereo -r {iFPS} -i {videoStream} -r {oFPS} -i {audioStream} -vcodec libx265 -crf {crf} {videoOut} >> ffmpeg.log 2>&1",
f"ffmpeg -ac 2 -y -channel_layout stereo -r {iFPS} -i {videoStream} \
-r {oFPS} -i {audioStream} -vcodec libx265 -crf {crf} {videoOut} >> ffmpeg.log 2>&1",
shell=True)
if ret==0:
removeFile(videoStream, audioStream)




def markedFileName(fName,mark):
pth,fNme = os.path.split(fName)
b,e = os.path.splitext(fNme)
return os.path.join(pth,b+f'_{mark}'+e)


def splitFilesInChunks(inFile, actTime, chunks=300):
# split in chunks of 5 minutes
def splitFilesInChunks(inFile, actTime, chunks=600):
# split in chunks of 10 minutes
fileSize = os.path.getsize(inFile)/1e6 # filesiz in mb
if fileSize <= 48.0: # telegram file size limit 50MB
print(f'Nothing to split, file is already small. Filesize: {fileSize} MB')
return [inFile]
files = []
nChnks = int(actTime/chunks)
for i in range(nChnks+1):
# sTime, eTime = i*chunks, (i+1)*chunks
# if eTime> actTime :
# eTime = actTime
fName = markedFileName(inFile,i+1)
# Put a _`n` at the end of the splitted file name
fName = f'_{i}'.join(os.path.splitext(inFile))
subprocess.call(
# f"ffmpeg -i {inFile} -ss {sTime} -to {eTime} {fName} >> ffmpeg.log 2>&1",
f"ffmpeg -i {inFile} -ss {i*chunks} -t {chunks} {fName} >> ffmpeg.log 2>&1",
f"ffmpeg -ss {i*chunks} -i {inFile} -t {chunks} -c copy {fName} >> ffmpeg.log 2>&1",
shell=True)
# put `ss` before the input file to properly copy the initial keyframes
files.append(fName)
return files

Expand Down

0 comments on commit 162a1b4

Please sign in to comment.