コード例 #1
0
ファイル: auto_rename.py プロジェクト: iynaix/renamer
def move_tv_episodes(dry_run=False):
    """
    handle tv episodes downloaded by sabnzbd
    """
    episode_dirs = []
    for d in loop_completed_dl_dirs():
        #need to fake an extension
        info = guessit.guess_video_info(str(d)+".avi")
        if info["type"] != "episode":
            continue
        episode_dirs.append(d)

    for d in episode_dirs:
        #look for the largest file
        vid = sorted(d.files(), key=lambda f: f.size)[-1]

        info = guessit.guess_video_info(str(vid))
        fname = "%(series)s S%(season)02dE%(episodeNumber)02d" % info
        fp = vid.rename("%s%s" % (fname, vid.ext))
        move_file(fp, HOME_DIR("Videos/TO WATCH"), dry_run)

    for d in episode_dirs:
        #remove the directory
        if not dry_run:
            d.rmtree()
コード例 #2
0
ファイル: dashboard.py プロジェクト: Toilal/guessitserver
    def guess_popover(filename):
        try:
            g = guessit.guess_video_info(filename)
            return ', '.join('%s: <b>%s</b>' % (k, v) for k, v in g.items())

        except Exception as e:
            return 'Exception occurred: %s' % e
コード例 #3
0
ファイル: subtitles.py プロジェクト: DoctorMalboro/touchandgo
def get_subtitle(magnet, lang):
    print("Obtaining subtitle (experimental, might take a while)")
    lt_session = session()
    params = {"save_path": "/tmp"}
    handle = add_magnet_uri(lt_session, magnet, params)
    while (not handle.has_metadata()):
        sleep(.1)
    info = handle.get_torrent_info()
    files = info.files()

    biggest_file = ("", 0)

    for file_ in files:
        if file_.size > biggest_file[1]:
            biggest_file = [file_.path, file_.size]

    print("Guessing data")
    filepath = biggest_file[0]
    guess = guess_video_info(filepath, info = ['filename'])
    video = Video.fromguess(filepath, guess)
    video.size = biggest_file[1]
    print("Donwloading Subtitle")
    subtitle = download_best_subtitles([video], {Language(lang)}, single=True)
    if not len(subtitle):
        subtitle = None
    else:
        subtitle = get_subtitle_path(video.name)
    lt_session.remove_torrent(handle)
    return subtitle
コード例 #4
0
    def guess_popover(filename):
        try:
            g = guessit.guess_video_info(filename)
            return ', '.join('%s: <b>%s</b>' % (k, v) for k, v in g.items())

        except Exception as e:
            return 'Exception occurred: %s' % e
コード例 #5
0
ファイル: guess_folders.py プロジェクト: iynaix/renamer
def handle_video_dir(d, dry_run=True):
    file_sizes = [f.size for f in d.walkfiles()]
    total_size = sum(file_sizes) * 1.0
    size_ratios = sorted([s / total_size for s in file_sizes], reverse=True)

    if size_ratios[0] >= 0.95:
        vid = sorted(d.walkfiles(), key=lambda f: f.size)[-1]

        info = guessit.guess_video_info(str(vid))
        if info["type"] == "movie":
            fp = vid.rename("%s%s" % (info["title"], vid.ext))
            move_file(fp, HOME_DIR("Videos/Movies"), dry_run)
        elif info["type"] == "episode":
            fname = "%(series)s S%(season)02dE%(episodeNumber)02d" % info
            fp = vid.rename("%s%s" % (fname, vid.ext))
            move_file(fp, HOME_DIR("Videos/TO WATCH"), dry_run)

        #remove the directory
        if not dry_run:
            d.rmtree()
    else:
        #multiple video files, rename them
        for f in d.files():
            rename(f, dry_run)
        #move the directory
        if not dry_run:
            fp = rename(d, dry_run)
            fp.move(HOME_DIR("Videos/TO WATCH"))
コード例 #6
0
ファイル: subtitles.py プロジェクト: damdev/touchandgo
def get_subtitle(magnet, lang):
    print("Explorando torrent")
    lt_session = session()
    lt_session.listen_on(6881, 6891)
    params = {"save_path": "/tmp"}
    handle = add_magnet_uri(lt_session, magnet, params)
    lt_session.start_dht()
    print "esperando"
    while (not handle.has_metadata()):
        sleep(.1)
    print "esperando"
    info = handle.get_torrent_info()
    print "esperando", info
    files = info.files()

    biggest_file = ("", 0)

    for file_ in files:
        if file_.size > biggest_file[1]:
            biggest_file = [file_.path, file_.size]

    print("Adivinando data")
    filepath = biggest_file[0]
    guess = guess_video_info(filepath, info = ['filename'])
    video = Video.fromguess(filepath, guess)
    video.size = biggest_file[1]
    print("Bajando el subtitulo para lang = " + lang)
    subtitle = download_best_subtitles([video], {Language(lang)}, single=True)
    if not len(subtitle):
        subtitle = None
    else:
        subtitle = get_subtitle_path(video.name)
    lt_session.remove_torrent(handle)
    return subtitle
コード例 #7
0
 def download(self, video_file):
     subtitle = None
     settings = get_settings()
     download_dir = settings.save_path
     log.info("Downloading subtitle")
     filepath = join(download_dir, video_file[0])
     guess = guess_video_info(filepath, info=['filename'])
     video = Video.fromguess(filepath, guess)
     video.size = video_file[1]
     try:
         subtitle = download_best_subtitles([video], {Language(self.lang)},
                                            single=True)
     except ValueError:
         pass
     if subtitle is not None and len(subtitle):
         log.info("CLAH %s %s", download_dir, video.name)
         subtitle = get_subtitle_path(
             join(
                 download_dir,
                 video.name.replace("(",
                                    "\(").replace(")",
                                                  "\)").replace(" ", "\ ")))
     log.info(
         "video_file: %s, filepath: %s, guess: %s, video: %s, "
         "subtitle: %s", video_file, filepath, guess, video, subtitle)
     return subtitle
コード例 #8
0
def get_subtitle(magnet, lang):
    print("Obtaining subtitle (experimental, might take a while)")
    lt_session = session()
    params = {"save_path": "/tmp"}
    handle = add_magnet_uri(lt_session, magnet, params)
    while (not handle.has_metadata()):
        sleep(.1)
    info = handle.get_torrent_info()
    files = info.files()

    biggest_file = ("", 0)

    for file_ in files:
        if file_.size > biggest_file[1]:
            biggest_file = [file_.path, file_.size]

    print("Guessing data")
    filepath = biggest_file[0]
    guess = guess_video_info(filepath, info=['filename'])
    video = Video.fromguess(filepath, guess)
    video.size = biggest_file[1]
    print("Donwloading Subtitle")
    subtitle = download_best_subtitles([video], {Language(lang)}, single=True)
    if not len(subtitle):
        subtitle = None
    else:
        subtitle = get_subtitle_path(video.name)
    lt_session.remove_torrent(handle)
    return subtitle
コード例 #9
0
ファイル: pymediabot.py プロジェクト: Fenisu/pymediabot
def find_all_files(path, subtitles):
    """It will find all the video files, and if required the subtitles matching
    the video filename.
    """
    if os.path.isdir(path):
        log.debug("Walking through: %s" % path)
        videofiles = list()
        for dirpath, dirnames, filenames in os.walk(path):
            for f in filenames:
                guessing, movie, multiepisode = guesstype(f)
                if guessing is not None and 'container' in guessing:
                    if guessing['container'] in extensions:
                        videofile = {'file': os.path.join(dirpath, f),
                                     'guess': guessing}
                        if multiepisode:
                            videofile['TVSM'] = multiepisode
                        elif movie:
                            videofile['movie'] = movie
                        videofiles.append(videofile)
                        log.debug("Found: %s" % path)
        #print(videofiles)
        return videofiles
    else:
        log.debug("The input was a movie.\n+ Movie found: %s [%s bytes]" %
                  (os.path.basename(path), os.stat(path).st_size))
        log.info("Input: %s" % os.path.basename(path))
        guessing = guessit.guess_video_info(path)
        return [{'file': os.path.join(dirpath, f), 'guess': guessing}]
コード例 #10
0
def get_subtitle(magnet, lang):
    print("Explorando torrent")
    lt_session = session()
    lt_session.listen_on(6881, 6891)
    params = {"save_path": "/tmp"}
    handle = add_magnet_uri(lt_session, magnet, params)
    lt_session.start_dht()
    print "esperando"
    while (not handle.has_metadata()):
        sleep(.1)
    print "esperando"
    info = handle.get_torrent_info()
    print "esperando", info
    files = info.files()

    biggest_file = ("", 0)

    for file_ in files:
        if file_.size > biggest_file[1]:
            biggest_file = [file_.path, file_.size]

    print("Adivinando data")
    filepath = biggest_file[0]
    guess = guess_video_info(filepath, info=['filename'])
    video = Video.fromguess(filepath, guess)
    video.size = biggest_file[1]
    print("Bajando el subtitulo para lang = " + lang)
    subtitle = download_best_subtitles([video], {Language(lang)}, single=True)
    if not len(subtitle):
        subtitle = None
    else:
        subtitle = get_subtitle_path(video.name)
    lt_session.remove_torrent(handle)
    return subtitle
コード例 #11
0
ファイル: Addic7ed.py プロジェクト: wackou/periscope
	def process(self, filepath, langs):
		''' main method to call on the plugin, pass the filename and the wished
		languages and it will query the subtitles source '''
                guessedData = guessit.guess_video_info(filepath)
                if guessedData['type'] == 'episode':
                        team = [ guessedData['releaseGroup'].lower() ] if 'releaseGroup' in guessedData else []
                        return self.query(guessedData['series'], guessedData['season'], guessedData['episodeNumber'], team, langs)
                else:
                        return []
コード例 #12
0
    def process_matches(self, matches):

        for filepath in matches:
            guess = guessit.guess_video_info(filepath)
            media_type = guess['type']

            if media_type == 'movie':
                self.process_movie(guess, filepath)
            elif media_type == 'episode':
                self.process_show(guess, filepath)
コード例 #13
0
ファイル: Addic7ed.py プロジェクト: wackou/periscope
    def process(self, filepath, langs):
        ''' main method to call on the plugin, pass the filename and the wished
		languages and it will query the subtitles source '''
        guessedData = guessit.guess_video_info(filepath)
        if guessedData['type'] == 'episode':
            team = [guessedData['releaseGroup'].lower()
                    ] if 'releaseGroup' in guessedData else []
            return self.query(guessedData['series'], guessedData['season'],
                              guessedData['episodeNumber'], team, langs)
        else:
            return []
コード例 #14
0
ファイル: guess_folders.py プロジェクト: iynaix/renamer
def rename_video(f, dry_run=True):
    """
    rename a video file using guessit info
    """
    info = guessit.guess_video_info(str(f))
    if info["type"] == "movie":
        fp = f.rename("%s%s" % (info["title"], f.ext))
        move_file(fp, HOME_DIR("Videos/Movies"), dry_run)
    elif info["type"] == "episode":
        fname = "%(series)s S%(season)02dE%(episodeNumber)02d" % info
        fp = f.rename("%s%s" % (fname, f.ext))
        move_file(fp, HOME_DIR("Videos/TO WATCH"), dry_run)
コード例 #15
0
 def analyse2(self, file):
     guess = guessit.guess_video_info(unicode(file), info = ['filename'])
     if Episode.isEpisode(guess):
         episode = Episode(guess, file)
         logging.info('Looks like a TV series episode: %s', episode)
         self.episodes.append(episode)
     elif Movie.isMovie(file, guess):
         movie = Movie(guess, file)
         logging.info('Looks like a movie: %s', movie)
         self.movies.append(movie)
     else:
         logging.error('Unhandled file type: %s', file)
コード例 #16
0
ファイル: subhd.py プロジェクト: henryforever14/subhd.py
def get_guessed_video_name(video_name):
    """Parse the video info from the filename

    Args:
        video_name: the filename of the video
    Returns:
        keyword: return video title, usually as movie name,
                 otherwise the series title, usually as drama name.

    """
    video_info = guess_video_info(video_name)
    return video_info.get("title") or video_info.get("series")
コード例 #17
0
ファイル: subhd.py プロジェクト: trulymadly/subhd.py
def get_guessed_video_name(video_name):
    '''Parse the video info from the filename

    Args:
        video_name: the filename of the video
    Returns:
        keyword: return video title, usually as movie name,
                 otherwise the series title, usually as drama name.

    '''
    video_info = guess_video_info(video_name)
    return video_info.get('title') or video_info.get('series')
コード例 #18
0
ファイル: main.py プロジェクト: vkefallinos/peerTV
def qmagnet(link):
	global s , ses
	print link
	downloaded=False
	for i in magnets:
		if "link" in magnets[i]:
			if magnets[i]["link"]==link:
				downloaded=True
				break
	if downloaded==False:		
		h = lt.add_magnet_uri(ses, str(link), params)		
		while (not h.has_metadata()):
			time.sleep(.1)
		info = h.get_torrent_info()
		size=0
		for i in info.files():
			if i.size>=size:
				size=i.size
				video=i.path
		video_info=guessit.guess_video_info(video)
		prio=h.piece_priorities()
		for i in xrange(int(0.03*len(prio)),len(prio)):
			h.piece_priority(i,0)
		movie = {}
		magnet={}
		try:
			movie['title'] = video_info["title"]
			movie["path"]="/home/pi/movies/"+video
			movie['year'] = video_info["year"]
			movie['quality'] = video_info["format"]
			movie['suffix'] = video_info["mimetype"]
		except:	
			movie['title']=h.name()
			movie["path"]="/home/pi/movies/"+video
		try:
			movie=fillInFromOmdb(movie)
		except:
			print "no info for movie"
		magnet["htmlmovie"]=movie
		magnet["link"]=link
		print movie["path"]

		magnets[h.name()]=magnet
		try:
			if "omdb" in magnet["htmlmovie"]:
				urllib.urlretrieve(magnet["htmlmovie"]["omdb"]['Poster'], filename=os.path.dirname(movie["path"])+'/poster.jpg')
				with open(os.path.dirname(movie["path"])+'/poster.jpg') as img:
					data=img.read()
					magnets.put_attachment(magnet,data,"poster.jpg","image/jpg")
		except:
			print "no poster"
		print 'saved : ', h.name()
コード例 #19
0
ファイル: TvSubtitles.py プロジェクト: wackou/periscope
	def process(self, filename, langs):
		''' main method to call on the plugin, pass the filename and the wished
		languages and it will query TvSubtitles.net '''

                guessedData = guessit.guess_video_info(filename)
                log.debug(filename)

		if guessedData['type'] == 'episode':
			subs = self.query(guessedData['series'], guessedData['season'], guessedData['episodeNumber'],
                                          guessedData.get('releaseGroup', []), langs)
			return subs
		else:
			return []
コード例 #20
0
def guessInfo(fileName, tvdbid=None):
    if not settings.fullpathguess:
        fileName = os.path.basename(fileName)
    guess = guessit.guess_video_info(fileName)
    try:
        if guess['type'] == 'movie':
            return tmdbInfo(guess)
        elif guess['type'] == 'episode':
            return tvdbInfo(guess, tvdbid)
        else:
            return None
    except Exception as e:
        print e
        return None
コード例 #21
0
    def process(self, filename, langs):
        ''' main method to call on the plugin, pass the filename and the wished
		languages and it will query TvSubtitles.net '''

        guessedData = guessit.guess_video_info(filename)
        log.debug(filename)

        if guessedData['type'] == 'episode':
            subs = self.query(guessedData['series'], guessedData['season'],
                              guessedData['episodeNumber'],
                              guessedData.get('releaseGroup', []), langs)
            return subs
        else:
            return []
コード例 #22
0
ファイル: manual.py プロジェクト: Smenus/nzbToMP4
def guessInfo(fileName):
    if not settings.fullpathguess:
        fileName = os.path.basename(fileName)
    guess = guessit.guess_video_info(fileName)
    try:
        if guess['type'] == 'movie':
            return tmdbInfo(guess)
        elif  guess['type'] == 'episode':
            return tvdbInfo(guess)
        else:
            return None
    except Exception as e:
        print e
        return None
コード例 #23
0
ファイル: categorize.py プロジェクト: mackbuvelot/py-expander
def get_path_video(filename):
    guess = guessit.guess_video_info(filename)

    if guess[u'type'] == u'episode':
        series = guess.get(u'series', u'').title()
        season = guess.get(u'season', u'')

        return config.TV_PATH.format(series=series, season=season)
    elif guess[u'type'] == u'movie':
        title = guess.get(u'title', u'').title()
        year = guess.get(u'year', u'')

        return config.MOVIE_PATH.format(title=title, year=year)
    else:
        return None
コード例 #24
0
    def processDir(path):
        folders = []

        logger.info("Searching %s for mediafiles to post-process ..." % (path))

        # search for single files and move them into there own folder for post-processing
        for mediafile in listMediaFiles(path):
            parentDir = os.path.dirname(mediafile)
            if parentDir == path:
                newPath = None
                fileExt = os.path.splitext(os.path.basename(mediafile))[1]

                try:
                    if fileExt in nzbtomedia.AUDIOCONTAINER:
                        f = beets.mediafile.MediaFile(mediafile)

                        # get artist and album info
                        artist = f.artist
                        album = f.album

                        # create new path
                        newPath = os.path.join(
                            parentDir, "%s - %s" %
                            (sanitizeName(artist), sanitizeName(album)))
                    elif fileExt in nzbtomedia.MEDIACONTAINER:
                        f = guessit.guess_video_info(mediafile)

                        # get title
                        title = None
                        try:
                            title = f['series']
                        except:
                            title = f['title']

                        if not title:
                            title = os.path.basename(mediafile)

                        newPath = os.path.join(parentDir, sanitizeName(title))
                except Exception, e:
                    logger.info("Exception from MediaFile for: %s: %s" %
                                (dir, e))

                # create new path if it does not exist
                if not os.path.exists(newPath):
                    makeDir(newPath)

                # move file to its new path
                shutil.move(mediafile, newPath)
コード例 #25
0
ファイル: web.py プロジェクト: yo-han/HandleBar
    def post(self): 	
		guess = guessit.guess_video_info(self.get_argument("filename"), info = ['filename'])
		data = ""
		
		if guess['type'] == "movie":
			results = tmdb.search(guess['title'])
			
			if results:
				data = tmdb.getMovieInfo(results[0]['id'])
			
		elif guess['type'] == "episode":
		
			tvdb = tvdb_api.Tvdb()
			data = tvdb[guess['series']].data
			
		self.render("metadata.tpl", metadata=data, guessit=guess, tabActive='metadata')
コード例 #26
0
ファイル: episodeMatcher.py プロジェクト: AndiH/UPnPtrakt
def getEpisodeInfo(rawString, reString='(.+)\((\d{1,2})\_(\d{1,2})\):'):
	name = season = episode = None 
	p = re.compile(reString)
	matched = p.search(rawString)
	if (matched):
		name = str(matched.group(1).rstrip())
		season = int(matched.group(2))
		episode = int(matched.group(3))
	else:
		if (not ('mkv' in rawString)):
			rawString = rawString + str('.mkv')
		guessed = guessit.guess_video_info(rawString)
		if (guessed['type'] == 'episode' and guessed.has_key('season')):
			name = str(guessed['series'])
			season = int(guessed['season'])
			episode = int(guessed['episodeNumber'])
	return (name, season, episode)
コード例 #27
0
def getEpisodeInfo(rawString, reString='(.+)\((\d{1,2})\_(\d{1,2})\):'):
	name = season = episode = None 
	p = re.compile(reString)
	matched = p.search(rawString)
	if (matched):
		name = str(matched.group(1).rstrip())
		season = int(matched.group(2))
		episode = int(matched.group(3))
	else:
		if (not ('mkv' in rawString)):
			rawString = rawString + str('.mkv')
		guessed = guessit.guess_video_info(rawString)
		if (guessed['type'] == 'episode'):
			name = str(guessed['series'])
			season = int(guessed['season'])
			episode = int(guessed['episodeNumber'])
	return (name, season, episode)
コード例 #28
0
    def processDir(path):
        folders = []

        logger.info("Searching %s for mediafiles to post-process ..." % (path))

        # search for single files and move them into there own folder for post-processing
        for mediafile in listMediaFiles(path):
            parentDir = os.path.dirname(mediafile)
            if parentDir == path:
                newPath = None
                fileExt = os.path.splitext(os.path.basename(mediafile))[1]

                try:
                    if fileExt in nzbtomedia.AUDIOCONTAINER:
                        f = beets.mediafile.MediaFile(mediafile)

                        # get artist and album info
                        artist = f.artist
                        album = f.album

                        # create new path
                        newPath = os.path.join(parentDir, "%s - %s" % (sanitizeName(artist), sanitizeName(album)))
                    elif fileExt in nzbtomedia.MEDIACONTAINER:
                        f = guessit.guess_video_info(mediafile)

                        # get title
                        title = None
                        try:
                            title = f['series']
                        except:
                            title = f['title']

                        if not title:
                            title = os.path.basename(mediafile)

                        newPath = os.path.join(parentDir, sanitizeName(title))
                except Exception, e:
                    logger.info("Exception from MediaFile for: %s: %s" % (dir, e))

                # create new path if it does not exist
                if not os.path.exists(newPath):
                    makeDir(newPath)

                # move file to its new path
                shutil.move(mediafile, newPath)
コード例 #29
0
ファイル: subtitles.py プロジェクト: jjconti/touchandgo
 def download(self, video_file):
     settings = get_settings()
     download_dir = settings['save_path']
     print("Downloading subtitle")
     log.info("Downloading subtitle")
     filepath = join(download_dir, video_file[0])
     guess = guess_video_info(filepath, info=['filename'])
     video = Video.fromguess(filepath, guess)
     video.size = video_file[1]
     subtitle = download_best_subtitles([video], {Language(self.lang)},
                                        single=True)
     if not len(subtitle):
         subtitle = None
     else:
         subtitle = get_subtitle_path(join(download_dir, video.name))
     log.info("video_file: %s, filepath: %s, guess: %s, video: %s"
              "subtitle: %s", video_file, filepath, guess, video, subtitle)
     return subtitle
コード例 #30
0
ファイル: subtitles.py プロジェクト: ldotlopez/zizi
def process(path, classifier, settings):
    bname = basename(path)

    # Use guessit, yes, really
    info = guessit.guess_video_info(bname)

    ftype = info.get('type', 'unknow')
    if ftype != 'episode':
        return [path]

    api = SubmanagerAPI(
        languages=settings.get_list('subtitles', 'languages'),
        info_sources=settings.get_list('subtitles', 'info sources'),
        subtitle_sources=settings.get_list('subtitles', 'subtitle sources')
    )
    try:
        (subfile, sub_info) = api.fetch_subtitles(path)[0]
    except IndexError:
        return [path]

    # In some cases the target has no title information.
    # sub_info contains title information that can be used to re-invoke
    # pattern_renaming plugin
    if not info.get('title') and sub_info.get('title'):
        old_path = path

        # Insert title into path
        (name, ext) = splitext(path)
        path = "{} - {}{}".format(name, sub_info.get('title'), ext)
        classifier.filesystem_op('move', old_path, path)

        # Re-run pattern renaming
        result = classifier.run_plugin('pattern_renaming', path, settings)
        if result:
            path = result[0]

    # Move subtitle to the appropiate location
    langcode = api.get_lang_code(sub_info['language'])
    sext = sub_info['sext']

    subpath = splitext(path)[0] + ("."+langcode+"." if langcode else '') + sext
    classifier.filesystem_op('move', subfile, subpath)

    return [path, subpath]
コード例 #31
0
ファイル: nearest_matches.py プロジェクト: ldotlopez/zizi
def process(path, classifier, settings=None):
    if not isfile(path):
        return [path]
    (dname, bname) = split(path)
    info = guessit.guess_video_info(path)

    for key in settings.options('nearest_matches'):
        (ftype, token) = key.split(':', 2)

        if info.get('type', 'unknow') == ftype and token in info:
            candidates = settings.getlist('nearest_matches', key, resep=',\s*')
            newvalue = difflib.get_close_matches(info[token], candidates, cutoff=0.6)
            if newvalue:
                bname = bname.replace(info[token], newvalue[0])
                break

    dst = join(dname, bname)
    if dst != path:
        classifier.filesystem_op('move', path, dst)

    return [dst]
コード例 #32
0
ファイル: utils.py プロジェクト: iynaix/renamer
def rename_episode(renamed):
    """
    renames a tv episode, given the namebase of a file
    """
    info = guessit.guess_video_info("%s.avi" % (renamed))

    if info["type"] != "episode":
        return renamed

    #not a tv series, even though it might look like one
    series_exceptions = ["techsnap"]
    if info["series"].lower() in series_exceptions:
        return renamed

    #probably a youtube / vimeo video
    if "episodeNumber" not in info or "series" not in info:
        return renamed

    try:
        return "%(series)s S%(season)02dE%(episodeNumber)02d" % info
    except KeyError:
        return renamed
コード例 #33
0
ファイル: auto_rename.py プロジェクト: iynaix/renamer
def move_movies(dry_run=False):
    """
    handle movies downloaded from 300mbunited, renaming them and moving them to
    the movies folder
    """
    movie_dirs = []
    for d in loop_completed_dl_dirs():
        #look for any movie directories
        #it shouldn't have many files
        file_count = len(d.listdir())
        if file_count > 10 or file_count == 0:
            continue

        #look at the distribution of file sizes
        file_sizes = [f.size for f in d.files()]
        total_file_sizes = sum(file_sizes)

        file_size_dist = [f.size * 1.0 / total_file_sizes for f in d.files()]

        #movie files should be more than 95% of total file size
        if sorted(file_size_dist)[-1] > 0.95:
            movie_dirs.append(d)

    for d in movie_dirs:
        vid = sorted(d.files(), key=lambda f: f.size)[-1]

        info = guessit.guess_video_info(str(vid))
        try:
            fp = vid.rename("%s%s" % (info["title"], vid.ext))
            move_file(fp, HOME_DIR("Videos/Movies"), dry_run)
        #not a movie file, just bail
        except KeyError:
            return

    for d in movie_dirs:
        #remove the directory
        if not dry_run:
            d.rmtree()
コード例 #34
0
ファイル: subtitles.py プロジェクト: Zopieux/touchandgo
 def download(self, video_file):
     subtitle = None
     settings = get_settings()
     download_dir = settings.save_path
     log.info("Downloading subtitle")
     filepath = join(download_dir, video_file[0])
     guess = guess_video_info(filepath, info=['filename'])
     video = Video.fromguess(filepath, guess)
     video.size = video_file[1]
     try:
         subtitle = download_best_subtitles([video], {Language(self.lang)},
                                            single=True)
     except ValueError:
         pass
     if subtitle is not None and len(subtitle):
         log.info("CLAH %s %s", download_dir, video.name)
         subtitle = get_subtitle_path(join(download_dir,
                                           video.name.replace("(", "\(")
                                           .replace(")", "\)")
                                           .replace(" ", "\ ")))
     log.info("video_file: %s, filepath: %s, guess: %s, video: %s, "
              "subtitle: %s", video_file, filepath, guess, video, subtitle)
     return subtitle
コード例 #35
0
ファイル: subtitles.py プロジェクト: iynaix/renamer
def is_valid_subtitle(sub):
    """
    returns True if the subtitle is valid, False otherwise
    """
    info = guessit.guess_video_info(sub.release)
    if info["type"] != "moviesubtitle":
        return False
    if info["container"] != "srt":
        return False

    #filter out those that are not english
    if "language" in info:
        if "english" not in repr(info["language"]).lower():
            return False
    if "subtitleLanguage" in info:
        if "english" not in repr(info["subtitleLanguage"]).lower():
            return False

    #uninterested in split srt files
    if "cdNumber" in info:
        return False

    return True
コード例 #36
0
    def guess(self):
        """Extrae los datos del nombre del archivo y los carga en las variables"""
        #TODO: esto se podria quitar, supongo, es mas que nada una lista de variables
        self.version = None
        self.serie = None
        self.temporada = None
        self.episodio = None
        self.titulo = None
        self.codec = None
        self.formato = None
        self.tamano = None
        self.tipo = None  #Episodio, película o desconocido

        #uso del módulo guessit para sacar los datos a partir del nombre del archivo
        guess = guessit.guess_video_info(self.archivo)
        if guess['type'] == 'episode':
            self.version = guess.get('releaseGroup')
            self.serie = guess.get('series')
            self.temporada = guess.get('season')
            self.episodio = guess.get('episodeNumber')
            self.titulo = guess.get('title')
            self.codec = guess.get('videoCodec')
            self.formato = guess.get('format')
            self.tamano = guess.get('screenSize')
            self.tipo = guess.get('type')

            self.buscar_por_nombre = True if self.version is not None else False
        #cuando hay nombres raros, tipo cuacuacua.avi, entra aquí
        elif guess['type'] == 'movie':
            self.tipo = guess.get('type')
            self.titulo = guess.get('title')
            self.buscar_por_nombre = False
        else:
            self.buscar_por_nombre = False

        return 0 if self.buscar_por_nombre == True else 1
コード例 #37
0
ファイル: core.py プロジェクト: fmacia/subtle
    def guess(self):
        """Extrae los datos del nombre del archivo y los carga en las variables"""
        #TODO: esto se podria quitar, supongo, es mas que nada una lista de variables
        self.version = None
        self.serie = None
        self.temporada = None
        self.episodio = None
        self.titulo = None
        self.codec = None
        self.formato = None
        self.tamano = None
        self.tipo = None #Episodio, película o desconocido

        #uso del módulo guessit para sacar los datos a partir del nombre del archivo
        guess = guessit.guess_video_info(self.archivo)
        if guess['type'] == 'episode':
            self.version = guess.get('releaseGroup')
            self.serie = guess.get('series')
            self.temporada = guess.get('season')
            self.episodio = guess.get('episodeNumber')
            self.titulo = guess.get('title')
            self.codec = guess.get('videoCodec')
            self.formato = guess.get('format')
            self.tamano = guess.get('screenSize')
            self.tipo = guess.get('type')

            self.buscar_por_nombre = True if self.version is not None else False
        #cuando hay nombres raros, tipo cuacuacua.avi, entra aquí
        elif guess['type'] == 'movie':
            self.tipo = guess.get('type')
            self.titulo = guess.get('title')
            self.buscar_por_nombre = False
        else:
            self.buscar_por_nombre = False
            
        return 0 if self.buscar_por_nombre == True else 1
コード例 #38
0
def is_video_file(fs_path):
    file_info = guessit.guess_video_info(fs_path)
    return ('mimetype' in file_info) and file_info['mimetype'].startswith("video/")
コード例 #39
0
ファイル: download.py プロジェクト: lsalvay/touchandgo
 def guess(self, path):
     if self._guess is None:
         self._guess = guess_video_info(path, info=['filename'])
     return self._guess
コード例 #40
0
    def processDir(path):
        folders = []

        logger.info("Searching %s for mediafiles to post-process ..." % (path))
        sync = [
            o for o in os.listdir(path)
            if os.path.splitext(o)[1] in ['.!sync', '.bts']
        ]
        # search for single files and move them into their own folder for post-processing
        for mediafile in [
                os.path.join(path, o) for o in os.listdir(path)
                if os.path.isfile(os.path.join(path, o))
        ]:
            if len(sync) > 0:
                break
            if os.path.split(mediafile)[1] in ['Thumbs.db', 'thumbs.db']:
                continue
            try:
                logger.debug("Found file %s in root directory %s." %
                             (os.path.split(mediafile)[1], path))
                newPath = None
                fileExt = os.path.splitext(mediafile)[1]
                try:
                    if fileExt in core.AUDIOCONTAINER:
                        f = beets.mediafile.MediaFile(mediafile)

                        # get artist and album info
                        artist = f.artist
                        album = f.album

                        # create new path
                        newPath = os.path.join(
                            path, "%s - %s" %
                            (sanitizeName(artist), sanitizeName(album)))
                    elif fileExt in core.MEDIACONTAINER:
                        f = guessit.guess_video_info(mediafile)

                        # get title
                        title = None
                        try:
                            title = f['series']
                        except:
                            title = f['title']

                        if not title:
                            title = os.path.splitext(
                                os.path.basename(mediafile))[0]

                        newPath = os.path.join(path, sanitizeName(title))
                except Exception as e:
                    logger.error(
                        "Exception parsing name for media file: %s: %s" %
                        (os.path.split(mediafile)[1], e))

                if not newPath:
                    title = os.path.splitext(os.path.basename(mediafile))[0]
                    newPath = os.path.join(path, sanitizeName(title))

                try:
                    newPath = newPath.encode(core.SYS_ENCODING)
                except:
                    pass

                # Just fail-safe incase we already have afile with this clean-name (was actually a bug from earlier code, but let's be safe).
                if os.path.isfile(newPath):
                    newPath2 = os.path.join(
                        os.path.join(os.path.split(newPath)[0], 'new'),
                        os.path.split(newPath)[1])
                    newPath = newPath2

                # create new path if it does not exist
                if not os.path.exists(newPath):
                    makeDir(newPath)

                newfile = os.path.join(
                    newPath, sanitizeName(os.path.split(mediafile)[1]))
                try:
                    newfile = newfile.encode(core.SYS_ENCODING)
                except:
                    pass

                # link file to its new path
                copy_link(mediafile, newfile, link)
            except Exception as e:
                logger.error("Failed to move %s to its own directory: %s" %
                             (os.path.split(mediafile)[1], e))

        #removeEmptyFolders(path, removeRoot=False)

        if os.listdir(path):
            for dir in [
                    os.path.join(path, o) for o in os.listdir(path)
                    if os.path.isdir(os.path.join(path, o))
            ]:
                sync = [
                    o for o in os.listdir(dir)
                    if os.path.splitext(o)[1] in ['.!sync', '.bts']
                ]
                if len(sync) > 0 or len(os.listdir(dir)) == 0:
                    continue
                folders.extend([dir])
        return folders
コード例 #41
0
 def guess(self, path):
     if self._guess is None:
         self._guess = guess_video_info(path, info=['filename'])
     return self._guess
コード例 #42
0
def process_player_info():
    if session.info_parsed or not availability.guessit_available:
        session.socket.send(MSG_A_PLAYER_INFO, session.info, destination=session.address)
        
        if session.extra_parsed:
            session.socket.send(MSG_A_PLAYER_EXTRA, session.extra, destination=session.address)
        # if session.extra is not parsed then there is no extra or it is still in construction
        
        return
    
    import guessit # this should be fast since it is pre-loaded here
    
    if DEBUG: print 'Processing player info for', session.video
    
    guess = guessit.guess_video_info(session.video)
    if DEBUG: print 'Guessit response:', guess.nice_string()
    
    if 'type' in guess.keys():
        ftype = guess['type']

        if ftype == 'episode':
            if 'series' not in guess.keys():
                session.info_parsed = True
                return
                
            show = camelcase(guess['series'])
            
            season = None
            if 'season' in guess.keys():
                season = guess['season']
            
            episode = None
            if 'episodeNumber' in guess.keys():
                episode = guess['episodeNumber']
            
            data = 'SHOW$' + show + '$'
            if season:
                data += 'S' + str(season)
            if episode:
                data += 'E' + str(episode)
                
            session.info = data
            
            if show and season and episode:
                extra_thread = threading.Thread(name='PlayerExtra|Episode', \
                                target=process_episode_info, args=(show, season, episode))
                extra_thread.setDaemon(True)
                extra_thread.start()
        
        elif ftype == 'movie':
            if 'title' not in guess.keys():
                session.info_parsed = True
                return
            
            title = camelcase(guess['title'])
                
            year = None
            if 'year' in guess.keys():
                year = guess['year']
            
            data = 'MOVIE$' + title + '$'
            if year:
                data += 'Y' + str(year)
                
            session.info = data
                
        else:
            session.info_parsed = True
            return
    
    session.info = session.info.encode('ascii', 'ignore')
    session.info_parsed = True
    
    session.socket.send(MSG_A_PLAYER_INFO, session.info, destination=session.address)
コード例 #43
0
ファイル: fetcher.py プロジェクト: movermeyer/subile
def get_video_info(video_path):
    video_path = os.path.abspath(video_path)
    video_name = os.path.basename(video_path)
    video_info = guessit.guess_video_info(video_name)
    video_info["filename"] = os.path.splitext(video_name)[0]
    return video_info
コード例 #44
0
	def handle_guess(self, filename):
		print filename
		return guessit.guess_video_info(String(filename), info = ['filename'])
コード例 #45
0
    def processDir(path):
        folders = []

        logger.info("Searching %s for mediafiles to post-process ..." % (path))
        sync = [ o for o in os.listdir(path) if os.path.splitext(o)[1] in ['.!sync','.bts'] ]
        # search for single files and move them into their own folder for post-processing
        for mediafile in [ os.path.join(path, o) for o in os.listdir(path) if
                            os.path.isfile(os.path.join(path, o)) ]:
            if len(sync) > 0:
                break
            if os.path.split(mediafile)[1] in ['Thumbs.db', 'thumbs.db']:
                continue
            try:
                logger.debug("Found file %s in root directory %s." % (os.path.split(mediafile)[1], path)) 
                newPath = None
                fileExt = os.path.splitext(mediafile)[1]
                try:
                    if fileExt in core.AUDIOCONTAINER:
                        f = beets.mediafile.MediaFile(mediafile)

                        # get artist and album info
                        artist = f.artist
                        album = f.album

                        # create new path
                        newPath = os.path.join(path, "%s - %s" % (sanitizeName(artist), sanitizeName(album)))
                    elif fileExt in core.MEDIACONTAINER:
                        f = guessit.guess_video_info(mediafile)

                        # get title
                        title = None
                        try:
                            title = f['series']
                        except:
                            title = f['title']

                        if not title:
                            title = os.path.splitext(os.path.basename(mediafile))[0]

                        newPath = os.path.join(path, sanitizeName(title))
                except Exception as e:
                    logger.error("Exception parsing name for media file: %s: %s" % (os.path.split(mediafile)[1], e))

                if not newPath:
                    title = os.path.splitext(os.path.basename(mediafile))[0]
                    newPath = os.path.join(path, sanitizeName(title))

                try:
                   newPath = newPath.encode(core.SYS_ENCODING)
                except: pass

                # Just fail-safe incase we already have afile with this clean-name (was actually a bug from earlier code, but let's be safe).
                if os.path.isfile(newPath):
                    newPath2 = os.path.join(os.path.join(os.path.split(newPath)[0], 'new'), os.path.split(newPath)[1])
                    newPath = newPath2

                # create new path if it does not exist
                if not os.path.exists(newPath):
                    makeDir(newPath)

                newfile = os.path.join(newPath, sanitizeName(os.path.split(mediafile)[1]))
                try:
                    newfile = newfile.encode(core.SYS_ENCODING)
                except: pass

                # link file to its new path
                copy_link(mediafile, newfile, link)
            except Exception as e:
                logger.error("Failed to move %s to its own directory: %s" % (os.path.split(mediafile)[1], e))

        #removeEmptyFolders(path, removeRoot=False)

        if os.listdir(path):
            for dir in [os.path.join(path, o) for o in os.listdir(path) if
                            os.path.isdir(os.path.join(path, o))]:
                sync = [ o for o in os.listdir(dir) if os.path.splitext(o)[1] in ['.!sync','.bts'] ]
                if len(sync) > 0 or len(os.listdir(dir)) == 0:
                    continue
                folders.extend([dir])
        return folders
コード例 #46
0
ファイル: guess.py プロジェクト: yo-han/HandleBarApp
import guessit
import json, sys

path = sys.argv[1];
guess = guessit.guess_video_info(path, info = ['filename'])

print json.dumps(guess)