0

I have a lot of videos all stored in different subfolders. All that videos have weird file names like "f4vd5sd1b5dsd41s415d". I also have a text file where there are the correct file names of each file. To know which video goes with which title, I added the file duration of the video I want to correspond with the title, so my text file looks like this:

name of video 1
length of video 1
name of video 2
length of video 2
...

I tried to make a script that compares the length of the video with the random file name with the file length of my text file, and if they match the title is added ( so one line backwards ) to the video in question.

To better explain it here's some work I did manually:

Before

After

Here's my scripting attempt, but I think it's incomplete:

# all imports
from moviepy.editor import VideoFileClip
import os
import shutil

#to copy all files that are in multiple subfolder into one subfolder
src = r'"my\\dir\\is\\here\\with\\all\\videos"'
dst = "my\\dir\\is\\here"

for path, subdirs, files in os.walk(src):
    for name in files:
        filename = os.path.join(path, name)


        if filename == filename in dst:
            os.rename(filename,filename+"123") #trying to prevent that equal filename receives another filename but does not work


        shutil.copy2 (filename, dst)

#to search all files and print file names

for root, dirs, files in os.walk (
    "my\\dir\\is\\here"):
    for f in files:
        if f.endswith ("mp4"):
            f_name, f_ext = os.path.splitext (f)
            print (f_name)
        if f.endswith ("mp4"):
            f = VideoFileClip (f) #does not work because movie.py doesn't go through subfolders like os.walk and spits an error
            dur = f.duration
            print (format (dur / 60, '.0f') + 'm' + ' ' + format (dur % 60, '.0f') + 's') #to convert it in min and sec


#to open and read txt file
with open ('2.txt') as fo:
    print (fo.read ())

#count lines of txt datei
with open("2.txt") as foo:
    lines = len(foo.readlines())

#if -schleife when dur of txt datei ==  dur of clip.duration with modulo operator(maybe works?)
if lines % dur:
    print(lines-1 ) # to say that every second line to match with the dur and if the dur and lines are equal move file 

Most of the code shown here is from solutions from other posts on StackOverflow. I am stuck writing the remainder of this script.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
frosta
  • 3
  • 4
  • Please **clarify your specific problem or add additional details to highlight exactly what you need**. As it's currently written, it’s hard to tell exactly what you're asking. See the [How to Ask](http://stackoverflow.com/help/how-to-ask) page for help clarifying this question – Pedro Lobito Apr 22 '17 at 17:04
  • @frosta Like Pedro, I'm confused about your goal. My best guess is that you have files with random names (eg, 0d3ba98...) and you want to assign those files meaningful names (the names in the text file), and you intend to use the length of the videos as the basis for deciding which random name links to which meaningful name. Is that correct or not? – FMc Apr 22 '17 at 17:14
  • 100% corrrect and I edited my post to be more clearly thanks a lot – frosta Apr 22 '17 at 17:17
  • Possible duplicate of [issue with movie.py with renaming script](http://stackoverflow.com/questions/43569556/issue-with-movie-py-with-renaming-script) – Manfred Radlwimmer Apr 25 '17 at 06:09
  • Another possible duplicate: https://stackoverflow.com/questions/43527156/program-or-script-to-rename-video-files-based-on-duration – Manfred Radlwimmer Apr 25 '17 at 06:10

1 Answers1

1

Here is a rough script. Please leave a comment if the script is broken, I wasn't able to test it because I don't have the appropriate libraries on my environment.

Explanation

I've split your requirements into separate functions. The function names along with the comments should be self-explanatory but here is a TLDR;

Walks through a directory and finds all mp4 files under the directory. Places a renamed copy of each mp4 file in your destination directory. A renaming rule is applied when the duration of the video file is close enough to be considered similar, as described in the is_close_enough function.

import os
import shutil
from moviepy.editor import VideoFileClip

# parses the renaming rules described in your text file
# returns a dictionary where:
#    key represents the duration to match
#    value represents the name to rename the video file to
def parse_rules(path):
  with open(path) as file:
    lines = file.readlines()
    rules = { lines[i+1]: lines[i] for i in range(0, len(lines), 2)}
  return rules # structure { duration: rename_to, ... }

# gets the duration of the video file
def duration(file):
  return VideoFileClip(file).duration

# determines whether the durations are close enough to be considered similar
def is_close_enough(duration1, duration2):
  return duration1 == duration2

# makes a copy of source file according to the renaming rules specified and puts the resulting file in the destination folder 
def rename_by_rules(src_file, dst_dir, rules):
  for k, rename_to in rules.items():
    if is_close_enough(k, duration(src_file)):
      shutil.copy2(src_file, os.path.join(dst_dir, rename_to)) 

# begins renaming your video files matched by duration according to the rules in your text file
rules = parse_rules('<replace with your text file>')
for base, dirs, files in os.walk('<replace with your source director>'):
  for file in files:
    if file.endswith('mp4'):
      rename_by_rules(os.path.join(base, file), '<replace by dest dir>', rules)
EyuelDK
  • 3,029
  • 2
  • 19
  • 27
  • thanks for the script really but could you please explain a bit the variables ? have some troubles to testrun it .... sorry again and thanks for the great effort ! – frosta Apr 22 '17 at 18:51
  • I hope this helps. But if you have specific questions about a line of code, please do let me know. – EyuelDK Apr 22 '17 at 19:18
  • yeah this helps really a lot thanks I have one general question : do I need to fill other variables except my filename for the txt file , the output dorectory and the input directory. If I mwill that three in the program doesn't crash but does nothing. tried to see what he did with the debug tool but I doesn't show me something either.... I'm also confused about the first block of your code and especially to the commentary after return rules... sorry to be so noobish – frosta Apr 22 '17 at 19:50
  • `lines = file.readlines()` returns a list each line in the file. `rules = { lines[i+1]: lines[i] for i in range(0, len(lines), 2)}` is called a dictionary comprehension, alike a list comprehension. It is just a short cut to initialize a dictionary. Refer to http://stackoverflow.com/questions/14507591/python-dictionary-comprehension for more info about this. The comment after the return is just to show the key => value relationship, where the key is a duration, and the value is the filename to rename to. – EyuelDK Apr 22 '17 at 20:20
  • ok thanks and for my general question again: do I need to fill other variables except my filename for the txt file , the output dorectory and the input directory? As said, if I fill these three, the program runs but do nothing ; nothing in the textbox or nothing in my files are moved , renamed or anything. is it normal? Am I doing something wrong? – frosta Apr 22 '17 at 20:31
  • ok so I tested it again ( this time with the right textfilename...was so dumb ) and yes I'm becoming an error – frosta Apr 22 '17 at 20:50
  • sorry that is out of my expertise. there seems to be something wrong with how you are using the video processing library. Can't help with that unless I take the time to read their documentation - and I hope you understand why I really don't feel like doing that.I hope the logic has helped but for further assistance with the functioning of the libraries you are using, please refer to other relevant threads. – EyuelDK Apr 22 '17 at 21:16
  • oh a last question or more an observation; when I launch the program before the traceback my ram goes up to my full ram capacity ( I have 8gb of ram and without the problem there are 4 at use so he fills up to 4 gigs of ram in seconds....) could that be the reason he crashes? – frosta Apr 22 '17 at 21:27
  • Sounds like there is a memory leak. In python, it's the garbage collector's job to clean up the unreferenced memory but from my experience, if you are filling up your memory quit fast the garbage collector may not be able to free up memory fast enough. I assume a lot of memory is being consumed at the `VideoFileClip(file)` line. To test this, just comment that out and replace it with a dud value. If so, place this code after the VideoFileClip object is created: `gc.collect()` - remember to import gc by `import gc` – EyuelDK Apr 22 '17 at 22:01
  • ok thanks and actually this wasn't the problem I restarted my pc and now it doesn't eat all my ram away anymoere my pc was just too long on.... so where could i get help now please? – frosta Apr 22 '17 at 22:14
  • so I could remove my problem by properly installing ffmpeg but got another instead : https://codeshare.io/axLKlB – frosta Apr 23 '17 at 09:13
  • You should ask a different thread about that. One related to ffmpeg or moviepy. – EyuelDK Apr 23 '17 at 09:14