How to automate downloading of subtitles for torrents - python-3.x

I know the title is really vague but anyways, I have a script for downloading the subtitles of a series or movie once the torrent is done downloading. The Input needs to be the filepath of the downloaded file. Conveniently uTorrent has a support for running the script once a torrent finishes downloading and has the filepath as one of its "parameters". I tried running the script with
C:\python\subtitles.py %D
where %D is the supported utorrent parameter for the filepath. This did not work as the script loaded then prompted for user input.Any help on how to automate this would be helpful.
from datetime import timedelta
from babelfish import Language
from subliminal import download_best_subtitles, region, save_subtitles, scan_videos
import os
# configure the cache
region.configure('dogpile.cache.dbm', arguments={'filename': 'cachefile.dbm'})
path = str(input("enter filepath:"))
# scan for videos newer than 1 week and their existing subtitles in a folder
videos = scan_videos(path, age=timedelta(days=7))
print("scan success")
# download best subtitles
subtitles = download_best_subtitles(videos, {Language('eng')})
print("downloads done")
# save them to disk, next to the video
for v in videos:
save_subtitles(v, subtitles[v])

That's because you're trying to get the "parameters" from stdin while your bittorrent client is passing the path as a command-line argument.
Replace path = str(input("enter filepath:")) with
import sys
path = sys.argv[1]
and it'll work.

Related

How to upload downloaded telegram media directly on google drive?

I'm working on the telethon download_media method for downloading images and videos. It is working fine (as expected). Now, I want to directly upload the download_media to my google drive folder.
Sample code looks something like:
from telethon import TelegramClient, events, sync
from telethon.tl.types import PeerUser, PeerChat, PeerChannel
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
drive = GoogleDrive(gauth)
gfile = drive.CreateFile({'parents': [{'id': 'drive_directory_path'}]})
api_id = #####
api_hash = ##########
c = client.get_entity(PeerChannel(1234567)) # some random channel id
for m in client.iter_messages(c):
if m.photo:
# below is the one way and it works
# m.download_media("Media/")
# I want to try something like this - below code
gfile.SetContentFile(m.media)
gfile.Upload()
This code is not working. How Can I define the google drive object for download_media?
Thanks in advance. Kindly assist!
The main problem is that according to PyDrive's documentation, setContentFile() expects a string with the file's local path, and then it just uses open(), so you're meant to use this with local files. In your code you're trying to feed it the media file so it won't work.
To upload a bytes file with PyDrive you'll need to convert it to BytesIO and send it as the content. An example with a local file would look like this:
drive = GoogleDrive(gauth)
file = drive.CreateFile({'mimeType':'image/jpeg', 'title':'example.jpg'})
filebytes = open('example.jpg', 'rb').read()
file.content = io.BytesIO(filebytes)
file.Upload()
Normally you don't need to do it this way because setContentFile() does the opening and conversion for you, but this should give you the idea that if you get the bytes media file you can just convert it and assign it to file.content and then you can upload it.
Now, if you look at the Telethon documentation, you will see that download_media() takes a file argument which you can set to bytes:
file (str | file, optional):
The output file path, directory, or stream-like object. If the path exists and is a file, it will be overwritten. If file is the type bytes, it will be downloaded in-memory as a bytestring (e.g. file=bytes).
So you should be able to call m.download_media(file=bytes) to get a bytes object. Looking even deeper at the Telethon source code it appears that this does return a BytesIO object. With this in mind, you can try the following change in your loop:
for m in client.iter_messages(c):
if m.photo:
gfile.content = io.BytesIO(m.download_media(file=bytes))
gfile.Upload()
Note that I only tested the PyDrive side since I currently don't have access to the Telegram API, but looking at the docs I believe this should work. Let me know what happens.
Sources:
PyDrive docs and source
Telethon docs and source

Video converter using movie.py project advice

Hello I am working on making a youtube video downloader, and a video converter to practice python language. With the video converter, I am trying to convert an mp4 file to a mp3 file. I want the user to input the specified path without having to open the text editor to do so. My issue is this. I am having trouble trying to figure out how I can possibly, if it is possible, to convert the file using the user's input. Can someone help me with this?
Here is the code I have so far:
import moviepy.editor as mp
#ask the user for the location of the file
loca = (input("Please input the location of the video file you wish to convert: "))
# Insert Local Video File Path
clip = mp.VideoFileClip(r'loca')
# Insert Local Audio File Path
clip.audio.write_audiofile(r'loca')
Just type extension to the file
If you can't imagine here's what's look like.
import moviepy.editor as mp
#ask the user for the location of the file
loca = (input("Please input the location of the video file you wish to convert: "))
filename = input("File name. : ")
# Insert Local Video File Path
clip = mp.VideoFileClip(loca)
# Insert Local Audio File Path
clip.audio.write_audiofile(filename)

how to compress uploaded files in django using 7zip subprocess.call method?

im trying to compress uploaded files in django using 7zip.
i have successfully implemented compression and decompression of files using 7zip in python but i am not able to figure out how to integrate the same with django uploaded file so that whenever a file is uploaded ,a 7zp format for the same file is create and stored in the disk.
Code used in python for compression :
import subprocess
from py7zr import unpack_7zarchive
import shutil
exe = r"C:\Program Files\7-Zip\7zG.exe"
source = r"C:\profiles\Living in the Light_ A guide to personal transformation.pdf"
target = r"C:\profiles\Living1.7z"
def compress(source,traget):
subprocess.call(exe + " a -t7z \"" + target + "\" \"" + source + "\" -mx=9")
print('file compressed')
def uncompress(target):
shutil.register_unpack_format('7zip', ['.7z'], unpack_7zarchive)
shutil.unpack_archive(target, r'C:\Users\098an\Pictures\Camera Roll')
print('file uncompressed')
I believe there are Django-specific tools that you must use other than 7-zip. One problem using 7-zip on the web is that, if the client's computer doesn't have it installed, your server won't run correctly.
I know two ways to work this out: if you are simply looking to compress images, you can refer to this dev.to article on compressing images specifically. The other way to work this out is requiring users to upload in the form of zip files as described here, but change the file extensions to .zip, .rar, or whatever you deem necessary
EDIT
There are ways to automatically zip all types of files such as this pypi package, but I'm not sure how those will work out as it's not a mainstream package. If you want to conserve upload space, try setting a size bound instead.

At what location does pafy save the downloaded file?

So I used the pafy library to download an audio file directly from youtube, but I don't know at what location the file is saved.
import pafy
video = pafy.new("dQw4w9WgXcQ")
bestaudio = video.getbestaudio()
bestaudio.download()
This is the code I used. The song was downloaded but I don't know where.
the file saved in the current working directory, you can know it using this code
import os
print(os.cwd())
and to change the current working directory use:
os.chdir(r"type your own path")

Write to %temp% with python?

I have a small program that works fine on my PC but I want to make it portable. What it does is download an image from the internet, set as desktop background, wait one minute and update the image. I know that I cannot write directly to folders like appdata, as I do not know the username of the person using the computer. I need to save the downloaded image somewhere, so I would save it in the windows Temp folder.
Some options I think would be to (However I don't know how to do this in python)
Use something like %temp% to access the folder.
Find out the username of the person running the program and insert into path
Use a variable for the username.
Use relative paths
I would like to try and not have to use another module not by default included in Python 3, as I want to cx_freeze it later on.
import pythoncom
from urllib import request
from win32com.shell import shell, shellcon
from time import sleep
def get_image():
f = open('C:\\Users\\MyUser\\Desktop\\Python\\bg\\bg.jpg', 'wb') #Open old image
f.write(request.urlopen('blalbla.com/foo/img.jpg').read()) #Get new image and write
f.close()
pathtoimg = 'C:\\Users\\MyUser\\Desktop\\Python\\bg\\bg.jpg'
count = 0
while 1:
get_image()
iad = pythoncom.CoCreateInstance(shell.CLSID_ActiveDesktop, None,
pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IActiveDesktop)
iad.SetWallpaper(pathtoimg, 0)
iad.ApplyChanges(shellcon.AD_APPLY_ALL)
count += 1
print(count)
sleep(60)
Use this to locate Temp:
import os
mytmpdir = os.environ['TEMP'] #Must be uppercase

Resources