Jump to content

How would could I make this more compact or efficient?

mbntr

This is a test, I just started using python and I'm trying to find some useful-ish projects

 

import pytube as pt
import urllib.request
import urllib.parse
import datetime
from moviepy.video.io.VideoFileClip import VideoFileClip
import os
import shutil
import re

lis = []

tr = True

print("\nYouTube video Downloader v2.1 BETA\n")

print("----------------------------------------------------------------------------------------------------------------"
      "-----------")

print("Write the titles of the videos or you want to download, as if you were using the youtube search bar (you can "
      "also write the\nchannel name to download the newest video from said channel), after you have finished "
      "press enter twice, before that you\nwill have to clarify the directory you want the files downloaded to...\n")

dirn = input(r"Please enter the download directory, then press enter: ")

dat = datetime.datetime.now()

dirnam = "YouTube videos " + dat.strftime("%B %d %Y")

dir = os.path.join(dirn, dirnam)
dir2 = os.path.join(dir, "mp3")
dir3 = os.path.join(dir, "mp4")

os.mkdir(r"" + dir + "")
os.mkdir(r"" + dir3 + "")

aud = input("Do you want to download the videos in mp3 or in mp4? -write mp3 or mp4-\n")

if aud in "mp3":
    os.mkdir(r"" + dir2 + "")

else:
    pass

print("\n\nNow write the titles...")

while tr:
    inp = input()

    if inp != "":
        lis.append(inp)

    else:
        n = 0
        for a in range(int(len(lis))):
            query_string = urllib.parse.urlencode({"search_query": lis[n]})
            html_content = urllib.request.urlopen("http://www.youtube.com/results?" + query_string)
            search_results = re.findall(r'href=\"\/watch\?v=(.{11})', html_content.read().decode())
            inp = "http://www.youtube.com/watch?v=" + search_results[0]


            class Video_to_audio:
                def __init__(self, url):
                    self.url = url

                def convert(self):
                    vid = pt.YouTube(self.url)
                    stri = vid.streams.filter(file_extension='mp4').get_highest_resolution()
                    print("\nDowloading: ", vid.title, "| ", str(datetime.timedelta(seconds=vid.length)), "hours",
                          "| ", vid.views, " views", "| ", "rating ", vid.rating, "\n")
                    stri.download(dir)

                    if aud in 'mp3':
                        print("Converting file to mp3 format...")

                        if vid.title[-1] == "." or vid.title[-1] == "?":

                            try:
                                vod = vid.title[:-1]
                                clip = VideoFileClip(os.path.join(dir, vod) + ".mp4")
                                clip.audio.write_audiofile(os.path.join(dir, vod) + ".mp3")

                            except:
                                print("\nError converting file: " + vid.title + ".mp4")

                        else:

                            try:
                                clip = VideoFileClip(os.path.join(dir, vid.title) + ".mp4")
                                clip.audio.write_audiofile(os.path.join(dir, vid.title) + ".mp3")

                            except:
                                print("\nError converting file: " + vid.title + ".mp4")

                    elif aud in 'mp4':
                        pass

                    else:
                        print("\nNo type was specified, defaulting to mp4 ")


            video = Video_to_audio(inp)
            video.convert()
            n += 1
        try:
            files = os.listdir(dir)
            if aud in "mp3":

                for f in files:
                    if re.search(".mp3", f):
                        f = os.path.join(dir, f)
                        shutil.move(f, dir2)

                for f in files:
                    if re.findall(".mp4", f):
                        f = os.path.join(dir, f)
                        shutil.move(f, dir3)
            else:
                for f in files:
                    if re.search(".mp4", f):
                        f = os.path.join(dir, f)
                        shutil.move(f, dir3)
        except:
            print("An error occurred when moving files...")

        input("\nAll videos have been downloaded and converted, press ENTER to exit")
        break

I made this for my grandfather who wants to download songs to use in his stereo player in the car.

Main PC [The Rig of Theseus]:

CPU: i5-8600K @ 5.0 GHz | GPU: GTX 1660 | RAM: 16 GB DDR4 3000 MHz | Case: Lian Li PC-O11 Dynamic | PSU: Corsair RM 650i | SSD: Corsair MP510 480 GB |  HDD: 2x 6 TB WD Red| Motherboard: Gigabyte Z390 Aorus Pro | OS: Windows 11 Pro for Workstations

 

Secondary PC [Why did I bother]:

CPU: AMD Athlon 3000G | GPU: Vega 3 iGPU | RAM: 8 GB DDR4 3000 MHz | Case: Corsair 88R | PSU: Corsair VS 650 | SSD: WD Green M.2 SATA 120 GB | Motherboard: MSI A320M-A PRO MAX | OS: Windows 11 Pro for Workstations

 

Server [Solution in search of a problem]:

Model: HP DL360e Gen8 | CPU: 1x Xeon E5-2430L v1 | RAM: 12 GB DDR3 1066 MHz | SSD: Kingston A400 120 GB | OS: VMware ESXi 7

 

Server 2 electric boogaloo [A waste of electricity]:

Model: intel NUC NUC5CPYH | CPU: Celeron N3050 | RAM: 2GB DDR3L 1600 MHz | SSD: Kingston UV400 120 GB | OS: Debian Bullseye

 

Laptop:

Model: ThinkBook 14 Gen 2 AMD | CPU: Ryzen 7 4700U | RAM: 16 GB DDR4 3200 MHz | OS: Windows 11 Pro

 

Photography:

 

Cameras:

Full Frame digital: Sony α7

APS-C digital: Sony α100

Medium Format Film: Kodak Junior SIX-20

35mm Film:

 

Lenses:

Sony SAL-1870 18-70mm ƒ/3.5-5.6 

Sony SAL-75300 75-300mm ƒ/4.5-5.6

Meike MK-50mm ƒ/1.7

 

PSA: No, I didn't waste all that money on computers, (except the main one) my server cost $40, the intel NUC was my old PC (although then it had 8GB of ram, I gave the bigger stick of ram to a person who really needed it), my laptop is used and the second PC is really cheap.

I like tinkering with computers and have a personal hatred towards phones and everything they represent (I daily drive an iPhone 7, or a 6, depends on which one works that day)

Link to comment
Share on other sites

Link to post
Share on other sites

12 minutes ago, mbntr said:

 


            files = os.listdir(dir)
            if aud in "mp3":

                for f in files:
                    if re.search(".mp3", f):
                        f = os.path.join(dir, f)
                        shutil.move(f, dir2)

                for f in files:
                    if re.findall(".mp4", f):
                        f = os.path.join(dir, f)
                        shutil.move(f, dir3)
            else:
                for f in files:
                    if re.search(".mp4", f):
                        f = os.path.join(dir, f)
                        shutil.move(f, dir3)

 

You can write that in a simpler way that doesn't make you loop twice for no reason:

            files = os.listdir(dir)
            for f in files:
            	if aud in "mp3":
                    if re.search(".mp3", f):
                        f = os.path.join(dir, f)
                        shutil.move(f, dir2)
                if re.search(".mp4", f):
                    f = os.path.join(dir, f)
                    shutil.move(f, dir3)

 

Also I don't understand why you're defining a class and why you're doing it inside a loop - that's both unnecessary and incredibly inefficient. If you want a class for whatever reason just define it at the start instead of redefining it at every loop iteration.

Don't ask to ask, just ask... please 🤨

sudo chmod -R 000 /*

Link to comment
Share on other sites

Link to post
Share on other sites

2 minutes ago, Sauron said:

You can write that in a simpler way that doesn't make you loop twice for no reason:


            files = os.listdir(dir)
            for f in files:
            	if aud in "mp3":
                    if re.search(".mp3", f):
                        f = os.path.join(dir, f)
                        shutil.move(f, dir2)
                if re.search(".mp4", f):
                    f = os.path.join(dir, f)
                    shutil.move(f, dir3)

 

Also I don't understand why you're defining a class and why you're doing it inside a loop - that's both unnecessary and incredibly inefficient. If you want a class for whatever reason just define it at the start instead of redefining it at every loop iteration.

good question, why did I do that... I could have used a function too.

How could I do it without the loop?

Main PC [The Rig of Theseus]:

CPU: i5-8600K @ 5.0 GHz | GPU: GTX 1660 | RAM: 16 GB DDR4 3000 MHz | Case: Lian Li PC-O11 Dynamic | PSU: Corsair RM 650i | SSD: Corsair MP510 480 GB |  HDD: 2x 6 TB WD Red| Motherboard: Gigabyte Z390 Aorus Pro | OS: Windows 11 Pro for Workstations

 

Secondary PC [Why did I bother]:

CPU: AMD Athlon 3000G | GPU: Vega 3 iGPU | RAM: 8 GB DDR4 3000 MHz | Case: Corsair 88R | PSU: Corsair VS 650 | SSD: WD Green M.2 SATA 120 GB | Motherboard: MSI A320M-A PRO MAX | OS: Windows 11 Pro for Workstations

 

Server [Solution in search of a problem]:

Model: HP DL360e Gen8 | CPU: 1x Xeon E5-2430L v1 | RAM: 12 GB DDR3 1066 MHz | SSD: Kingston A400 120 GB | OS: VMware ESXi 7

 

Server 2 electric boogaloo [A waste of electricity]:

Model: intel NUC NUC5CPYH | CPU: Celeron N3050 | RAM: 2GB DDR3L 1600 MHz | SSD: Kingston UV400 120 GB | OS: Debian Bullseye

 

Laptop:

Model: ThinkBook 14 Gen 2 AMD | CPU: Ryzen 7 4700U | RAM: 16 GB DDR4 3200 MHz | OS: Windows 11 Pro

 

Photography:

 

Cameras:

Full Frame digital: Sony α7

APS-C digital: Sony α100

Medium Format Film: Kodak Junior SIX-20

35mm Film:

 

Lenses:

Sony SAL-1870 18-70mm ƒ/3.5-5.6 

Sony SAL-75300 75-300mm ƒ/4.5-5.6

Meike MK-50mm ƒ/1.7

 

PSA: No, I didn't waste all that money on computers, (except the main one) my server cost $40, the intel NUC was my old PC (although then it had 8GB of ram, I gave the bigger stick of ram to a person who really needed it), my laptop is used and the second PC is really cheap.

I like tinkering with computers and have a personal hatred towards phones and everything they represent (I daily drive an iPhone 7, or a 6, depends on which one works that day)

Link to comment
Share on other sites

Link to post
Share on other sites

12 minutes ago, mbntr said:

good question, why did I do that... I could have used a function too.

How could I do it without the loop?

I can't tell if you need the while loop because you didn't comment anything :P but the declaration of the class or function can be done at the top of the file, right after the imports - that way it's done once (which is all you need) and then you can just call it inside the loop.

Don't ask to ask, just ask... please 🤨

sudo chmod -R 000 /*

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×