Esempio n. 1
0
    def process_folder(self, path: str):

        logging.info("----------------------------\n{0}".format(path))
        print("\n{0}".format(path))

        file_list = listFiles(path)

        parent_dir = os.path.abspath(os.path.join(path,
                                                  os.pardir)) + os.path.sep
        total_duration = 0
        smarthash_path_info = {}
        num_video_files = 0

        # extract metadata into a path -> json-metadata map
        for file in file_list:
            ext = os.path.splitext(file)[1].lower()
            # ignore extensions blacklist
            if ext in blacklist_media_extensions:
                continue

            file_path = os.path.join(parent_dir, file)
            mime_type = get_mime_type(file_path)
            mime_prefix = mime_type.split("/")[0]

            if mime_prefix in [
                    "audio", "video"
            ] or ext in whitelist_video_extensions or ext in whitelist_audio_extensions:
                smarthash_info = OrderedDict()
                smarthash_info['mediainfo'] = []
                if mime_type:
                    smarthash_info['mime_type'] = mime_type

                media_info = MediaInfo.parse(file_path)
                for track in media_info.tracks:
                    track_map = track.to_data()

                    # remove the full path for privacy's sake
                    if track_map['track_type'] == "General":
                        track_map['complete_name'] = track_map[
                            'complete_name'].replace(parent_dir, "")
                        track_map['folder_name'] = track_map[
                            'folder_name'].replace(parent_dir, "")
                        if 'duration' in track_map:
                            total_duration += track_map['duration']

                    smarthash_info['mediainfo'].append(track_map)

                # extract audio tags
                if mime_prefix == "audio" or ext in whitelist_audio_extensions:
                    smarthash_info['tags'] = OrderedDict()

                    mutagen_file = mutagen.File(file_path)  # easy=True

                    if not mutagen_file:
                        continue

                    tags = {}
                    for k in mutagen_file:
                        # filter out >1500 char (presumably binary) tags, except for comment/lyrics
                        if hasattr(mutagen_file[k], 'text') and \
                                (len(mutagen_file[k].text) < 1500 or k in ["USLT", "COMM"]) and len(mutagen_file[k].text):
                            tags[k] = [str(x) for x in mutagen_file[k].text]
                        elif isinstance(mutagen_file[k], list):
                            tags[k] = [str(x) for x in mutagen_file[k]]

                    for tag in sorted(tags):
                        smarthash_info['tags'][tag] = tags[tag]

                    if isinstance(mutagen_file.tags, VCFLACDict):
                        smarthash_info['tag_type'] = 'FLAC'
                    elif isinstance(mutagen_file.tags, ID3):
                        smarthash_info['tag_type'] = 'ID3'
                    smarthash_info['length'] = mutagen_file.info.length
                    smarthash_info['bitrate'] = mutagen_file.info.bitrate

                # Xing frame info
                if mime_type == "audio/mpeg" or ext == ".mp3":
                    smarthash_info['mp3_info'] = Mp3Info(file_path)

                # count the number of video files
                if (mime_prefix == "video" or ext in whitelist_video_extensions
                    ) and ext not in blacklist_media_extensions:
                    num_video_files += 1

                smarthash_path_info[file] = smarthash_info

        # read nfos from main path
        nfo_filenames = [
            f for f in os.listdir(path)
            if os.path.isfile(os.path.join(path, f))
        ]
        nfo_filenames = [
            f for f in nfo_filenames if f.lower().endswith(".nfo")
        ]

        nfos = []
        for f in nfo_filenames:
            nfos.append(read_nfo(os.path.join(path, f)))

        # manual nfo path
        if self.args.nfo_path:
            if os.path.isfile(self.args.nfo_path) and self.args.nfo_path.lower(
            ).endswith(".nfo"):
                nfos.append(read_nfo(self.args.nfo_path))
            elif os.path.isdir(self.args.nfo_path):
                nfo_filenames = [
                    f for f in os.listdir(self.args.nfo_path)
                    if os.path.isfile(os.path.join(self.args.nfo_path, f))
                ]

                nfo_filenames = [
                    f for f in nfo_filenames if f.lower().endswith(".nfo")
                ]
                for f in nfo_filenames:
                    nfos.append(read_nfo(os.path.join(self.args.nfo_path, f)))

        imdb_id = None
        genre = None
        nfo = ''

        for curr_nfo in nfos:
            imdb_id_match = re.findall(r"imdb\.com/title/tt(\d{7}\d?)",
                                       curr_nfo)
            if imdb_id_match:
                imdb_id = imdb_id_match[0]
                nfo = curr_nfo

        # default nfo
        if len(nfos) > 0 and not imdb_id:
            nfo = nfos[0]

        if 'imdb-id' in self.plugins[
                self.args.plugin].options and self.args.imdb_id:
            # manual imdb_id override
            imdb_id = self.args.imdb_id

        # make sure the IMDb ID exists
        if imdb_id:

            # imdb._logging.setLevel("error")
            print('IMDb querying...\r', end='\r'),
            imdb_site = imdb.IMDb()

            imdb_movie = imdb_site.get_movie(imdb_id)
            if not imdb_movie:
                cprint("Invalid IMDb ID: {0}".format(imdb_id), "red")
                sys.exit(1)
            logging.info("IMDb verified: \"{0}\"".format(imdb_movie))

            genre = choose_genre(imdb_movie['genres'])

        params = {
            'blacklist_file_extensions':
            [x.lower() for x in blacklist_file_extensions],
            'blacklist_path_matches':
            [x.lower() for x in blacklist_path_matches],
            'comment':
            "Generated with SmartHash {0}".format(smarthash_version),
            'smarthash_version':
            smarthash_version,
        }

        self.plugins[self.args.plugin].early_validation(
            path, {
                'args': self.args,
                'smarthash_info': smarthash_path_info,
                'title': os.path.basename(path),
                'imdb_id': imdb_id,
                'genre': genre,
                'params': params
            })

        # hash the folder
        metainfo = make_meta_file(path, None, params=params, progress=prog)
        #print()

        # lookup gathered metadata and insert into the torrent file metainfo
        for file in metainfo['info']['files']:
            file_path = os.path.join(os.path.basename(path), *file['path'])

            if file_path in smarthash_path_info:
                file['smarthash_info'] = json.dumps(
                    smarthash_path_info[file_path])

        images_per_video_file = 4
        if num_video_files in [2, 3]:
            images_per_video_file = 2
        elif num_video_files > 3:
            images_per_video_file = 1

        formatted_mediainfo = ""
        extracted_images = []

        # extract MediaInfo
        for file in metainfo['info']['files']:
            file_path = os.path.join(path, *file['path'])
            ext = os.path.splitext(file_path)[1].lower()
            path_key = os.path.join(metainfo['info']['name'], *file['path'])
            mime_type = smarthash_path_info[path_key][
                'mime_type'] if path_key in smarthash_path_info else get_mime_type(
                    file_path)
            mime_prefix = mime_type.split("/")[0]

            # for video files, compose a standard(ish) MediaInfo text output
            if (mime_prefix == "video" or ext in whitelist_video_extensions
                ) and ext not in blacklist_media_extensions:
                if formatted_mediainfo != "":
                    formatted_mediainfo += "\n{0}\n".format("-" * 70)
                formatted_mediainfo += MIFormat.MItostring(
                    smarthash_path_info[os.path.join(
                        os.path.basename(path), *file['path'])]['mediainfo'])

                if "video-screenshots" in self.plugins[
                        self.args.plugin].options:
                    extracted_images.append(
                        extractImages(file_path, images_per_video_file))

        # collect the dataset for the plugin
        data = {
            'smarthash_version': smarthash_version,
            'args': self.args,
            'path': path,
            'title': os.path.split(path)[-1],
            'total_duration': total_duration,
            'mediainfo': formatted_mediainfo,
            'extracted_images': extracted_images,
            'torrent_file': metainfo.gettorrent(),
            'nfo': nfo,
        }

        if imdb_id:
            data['imdb_id'] = imdb_id
        if genre:
            data['genre'] = genre

        try:
            self.plugins[self.args.plugin].handle(data)
            cprint("Done{0}\n".format(" " * 40), 'green', end='\r')
        except PluginError as e:
            cprint(e.error, "red")
        except ServerError:
            cprint("Server error, retrying...", "red")
            time.sleep(1)
            self.process_folder_wrapper(path)
Esempio n. 2
0
from numpy import nan
from bs4 import BeautifulSoup
import requests
import re
import time

#the input to this program is a url to a public IMDB movie list
listpath = 'https://www.imdb.com/list/ls045539551/'
listsoup = BeautifulSoup(requests.get(listpath).text, 'lxml')
movie_list = [[
    re.sub('(^.*?tt)', '',
           header.find('a')['href'])[0:7],
    header.find('a').contents[0]
] for header in listsoup.find_all(class_="lister-item-header")]

ia = imdb.IMDb()

df = pandas.DataFrame(columns=[
    'movie_title', 'imdb_movie_id', 'movie_rating', 'review_title',
    'review_date', 'review_author', 'review_rating', 'review_helpful',
    'review_not_helpful', 'review_source', 'review_content'
])  # initialise data frame

index = 0
print('Loading IMDB reviews for:')
x = 6
for i in range(x, len(movie_list) - 1):  # for each movie
    print(movie_list[i][1])
    mo_rating = ia.get_movie_vote_details(
        movie_list[i][0])['data']['arithmetic mean']
Esempio n. 3
0
try:
    import imdb
except ImportError:
    print('You bad boy!  You need to install the IMDbPY package!')
    sys.exit(1)


if len(sys.argv) != 2:
    print('Only one argument is required:')
    print('  %s "company name"' % sys.argv[0])
    sys.exit(2)

name = sys.argv[1]


i = imdb.IMDb()

out_encoding = sys.stdout.encoding or sys.getdefaultencoding()

try:
    # Do the search, and get the results (a list of company objects).
    results = i.search_company(name)
except imdb.IMDbError as e:
    print("Probably you're not connected to Internet.  Complete error report:")
    print(e)
    sys.exit(3)

# Print the results.
print('    %s result%s for "%s":' % (len(results),
                                     ('', 's')[len(results) != 1],
                                     name))
import os
import functools
import glob
import argparse
import re
import requests
import imdb
import enzyme
import pdb
from io import BytesIO
import PIL.ImageTk
import PIL.Image
import tkinter

imdb_interface = imdb.IMDb()

TRACE = False

UPDATE_ID = False

IMDB_KINDS = [
    "tv series",
    "movie",
    "episode",
    "video movie",
    "tv movie",
    "short",
    "video game",
    "tv miniseries"
]
Esempio n. 5
0
import imdb
import csv
import codecs

# import unicodedata

# this code add director and cast info to the links.csv file

ia = imdb.IMDb(accessSystem='http')  # fetch from imdb web server

file_name = 'datasets/links.csv'

old = open(file_name, 'rb')
new = codecs.open('modified.csv', 'wb', 'utf-8')
reader = csv.reader(old, delimiter=',')
next(reader)

new.write('movieId,imdbId,tmdId,director,cast\n')

for row in reader:
    id = row[1]
    m = ia.get_movie(id)

    director = ''
    cast_list = []
    cast = []

    if m.get('director'):
        director = m.get('director')[0].get('name')

    if m.get('cast'):
    def sendData(self):
        """Compute result of widget processing and send to output"""
        # Skip if title list is empty:
        if self.myBasket == list():
            self.infoBox.setText(
                "Your corpus is empty, please add some movies first",
                "warning")
            return

        # Clear created Inputs.
        self.clearCreatedInputs()

        self.controlArea.setDisabled(True)

        # Initialize progress bar.
        progressBar = ProgressBar(self, iterations=len(self.myBasket))

        # Attempt to connect to Genius and retrieve lyrics...
        selectedSongs = list()
        list_review = list()
        annotations = list()
        try:
            for item in self.myBasket:
                ia = imdb.IMDb()
                movie = ia.get_movie_reviews(item['id'])
                list_review.append(movie)
                # 1 tick on the progress bar of the widget
                progressBar.advance()

        # If an error occurs (e.g. http error, or memory error)...
        except:
            # Set Info box and widget to "error" state.
            self.infoBox.setText("Couldn't download data from imdb", "error")
            self.controlArea.setDisabled(False)
            return

        # Store movie critics strings in input objects...
        for movie in list_review:
            #for key, value in movie.items():
            #try:
            data = movie.get('data', "")
            reviews_data = data.get('reviews')
            for review in reviews_data:
                reviews = review.get('content')
                newInput = Input(reviews)
                self.createdInputs.append(newInput)
                new_dict = review.copy()
                annotations.append(new_dict)
        """
            except:
                self.infoBox.setText(
                "The movie has no associated reviews",
                "warning"
            )
            self.controlArea.setDisabled(False)
            return
        """

        # If there's only one item, the widget's output is the created Input.
        if len(self.createdInputs) == 1:
            self.segmentation = self.createdInputs[0]

        # Otherwise the widget's output is a concatenation...
        else:
            self.segmentation = Segmenter.concatenate(
                self.createdInputs,
                import_labels_as=None,
            )

        # Annotate segments...

        for idx, segment in enumerate(self.segmentation):
            segment.annotations.update(annotations[idx])
            self.segmentation[idx] = segment

        # Clear progress bar.
        progressBar.finish()

        self.controlArea.setDisabled(False)

        # Set status to OK and report data size...
        message = f"{len(self.segmentation)} segment@p sent to output"
        message = pluralize(message, len(self.segmentation))
        numChars = 0
        for segment in self.segmentation:
            segmentLength = len(Segmentation.get_data(segment.str_index))
            numChars += segmentLength
        message += "(%i character@p)." % numChars
        message = pluralize(message, numChars)
        self.infoBox.setText(message)

        self.send('Segmentation', self.segmentation, self)
        self.sendButton.resetSettingsChangedFlag()
Esempio n. 7
0
import shutil
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Optional

import imdb
from selenium.webdriver.common.by import By

from chromedriver import init_browser
from subtitles import get_embedded_subtitles, merge_all, VALID_FFMPEG_SUFFIXES
from util import parse_movie_name_from_string, recursive_iterdir, sanitize_name

IMDB_API = imdb.IMDb()

MOVIE_SUFFIXES = ['.mp4', '.mkv', '.avi']


@dataclass
class Movie:
    name: str
    year: int

    def __str__(self):
        return f'{self.name} ({self.year})'


# # # # # IMDB API


def query_movie_data_imdb(movie_filename: str) -> Movie:
Esempio n. 8
0
def test():
    i = imdb.IMDb()
    film = i.search_movie('avatar')[0]
    fichier = File.objects.all()[0]
    data = store_movie(film, fichier)
Esempio n. 9
0
def assistant(command):
    "if statements for executing commands"
    #os.system('nircmd.exe killprocess wmplayer.exe')


        

    if command == "hello1" or command == "hi1" or command=="hey1":
        print("hello ")
        talkToMe("hello sir")
    elif 'clear'==command:
        os.system("cls")

    elif ('from' in command or 'what' in command or 'where' in command or 'who' in command or 'whose' in command or 'when' in command or 'how' in command or 'whom' in command or 'why' in command or 'which' in command):
        #talkToMe('I don\'t know what you mean!')
        try:
            request = ai.text_request()
            request.query = command
            response = request.getresponse().read()
            output = json.loads(response)
            answer = output["result"]["fulfillment"]["speech"]
            #print('answer:',answer)
            #talkToMe(answer)

            if(answer=="" or answer=="not found"):
                #talkToMe(answer+" on layer 1") 
                try:
                    
                    client = wolframalpha.Client("4E3H79-A3ARKHYKU9")
                    #print('command:',command)
                    res = client.query(command)
                    answer = next(res.results).text
                    #print(answer)
                    talkToMe(answer)
                    #talkToMe("improve your internet speed")
                except:
                    try:
                        
                        print("IN WIKI")
                        talkToMe(wikipedia.summary(command))
                        #talkToMe("improve your internet speed")
                    except:
                        talkToMe("Sorry I got nothing, do you want me to search on google?")
                        if(typeCommand()=='yes'):
                            print("IN gsearch")
                            gsearch(command)
                        else:
                            talkToMe("OK, ask me something else.")
            else:
                talkToMe(answer)
                pass
        except:
            pass

    elif command == "what time is it" or command == "tell me time" or command == "what's the time" or command == "time" or command == "what is today" or command == "what's today" :
        t = time.asctime(time.localtime(time.time()))
        talkToMe(t)

    elif 'send text' in command or 'send sms' in command:
    	sendsms(command)

    elif '-' in command or '+' in command or '*' in command or '/' in command or '%' in command:
        try:
            talkToMe(str(eval(command)))
        except:
            talkToMe("not a valid equation")

    elif command == "bye" or command == "buy" or command=='exit':
        if hr >= 20 and hr <=24:
            print("Good night\n")
            talkToMe("Good night")
            sys.exit()
        else:
            print("see you again \n")
            talkToMe("see you again ")
            sys.exit()

    elif command == "how are you1":
        print("I'm good. How are you?\n")
        talkToMe("I'm good. How are you?")

    elif 'stop' in command:
        #engine.stop()
        talkToMe(command)

    elif command == "ok1" or command == 'okay1' or command == 'yeah1':
        print("Yes")
        talkToMe("yes")
    

    elif 'open' in command:

        if 'website' in command:
            reg_ex = re.search('open website (.+)', command)
            if reg_ex:
                domain = reg_ex.group(1)
                url = 'https://www.' + domain
                webbrowser.open(url)
                print('Done!')

        elif 'notes' in command or 'note' in command:
            os.system('start "" "D:\\PYTHON\\PROJECT\\Notes.txt"')
        
        else:
            #command = 'open notepad'
            command = command.replace('open ',"")
            #command = command.replace(" ","")
            
            os.system('nircmd sendkeypress rwin')
            for i in command:
                os.system('nircmd sendkeypress '+i)
            os.system('nircmd sendkeypress enter')


    elif 'movie' in command:
        command =  command.replace("movie","")
        command =  command.replace("about","")
        command = command.title()

        
        try:
            print("Name of a movie:"+command.replace("about movie",""))
            app = imdb.IMDb()
            results = app.search_movie(command)
            #if not results:
            #breturn "error 404"
            first = results[0]
            ID = first.movieID
            data = app.get_movie(ID)
            talkToMe("Year: "+str(data['year']))
            talkToMe("IMDb ratings: "+str(data['rating']))
        except:
           talkToMe("Error 404 not found")


    elif 'search' in command or 'google' in command or 'images of' in command or 'image of' in command or 'google map' in command:
        
        if 'images' in command:
            url = "https://www.google.com/search?tbm=isch&q={}".format(command.replace("images of", ""))
            webbrowser.open(url)

        
        #command=command.replace('on',"")
        elif 'google map' in command:
            url = "https://www.google.co.in/maps/place/" + command.replace("google map","")
            webbrowser.open(url)

        else:
            command=command.replace('google',"")
            command=command.replace('search',"")
            gsearch(command)






    elif 'youtube' in command or "video" in command:

        command=command.replace("on","")
        command=command.replace("search","")

        if 'play' in command:
            command=command.replace("play","")
            command=command.replace("on","")
            command=command.replace("youtube","")
            try:
                def ytPlayer(word):
                    a=[]
                    #word = input()

                    url = 'https://www.youtube.com/results?search_query=+'+word
                    yt='https://www.youtube.com'
                    #webbrowser.open_new_tab(url)

                    class MyOpener(FancyURLopener):
                        version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'   # Set this to a string you want for your user agent

                    myopener = MyOpener()
                    page = myopener.open(url).read()
                    webpage = page.decode('utf-8')

                    soup = bs.BeautifulSoup(webpage,'lxml')

                    div = soup.body
                    for data in div.find_all(href=True):
                        a.append(data.get('href'))

                #print(a)

                    matching = [s for s in a if '/watch?' in s]
                # print(matching[0])

                    ytplaylink = yt+matching[0]

                # print(ytplaylink)
                # pwrshllink= 'powershell -command Invoke-WebRequest '+ytplaylink+' -OutFile '+word+'.mp3'
                    webbrowser.open_new_tab(ytplaylink)
                    

                ytPlayer(command)
                return
            except:
                ytPlayer(command)

        if "download" in command:
            command=command.replace("video","")
            command=command.replace("download","")
            a1=[]
            a11=[]
            word1 =command #input('ENTER THE VIDEO NAME TO DOWNLOAD')

            url1 = 'https://www.youtube.com/results?search_query=+'+word1
            yt1='https://www.youtube.com'
            #webbrowser.open_new_tab(url)

            class MyOpener1(FancyURLopener):
                version1 = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'   # Set this to a string you want for your user agent
            myopener1 = MyOpener1()
            page1 = myopener1.open(url1).read()
            webpage1 = page1.decode('utf-8')

            soup1 = bs.BeautifulSoup(webpage1,'lxml')

            div1 = soup1.body
            for data1 in div1.find_all(href=True):
                a1.append(data1.get('href'))

            #print(a)

            matching1 = [s1 for s1 in a1 if '/watch?' in s1]

            ytplaylink1 = yt1+matching1[0]

            print(ytplaylink1)
            #os.walk(r"D:\ArmanK\python_programs\SUBLIME_FILES\SpeechRecog\video")
            def download():
                quality=input('WHICH QUALITY DO YOU WANT ME TO DOWNLOAD?')
                if '' in quality:
                    pass
                if '240' in quality:
                    r=os.system('"cd /d E:\\VIDEOS" && youtube-dl -f 5 '+ytplaylink1)
                if '360' in quality:
                    r=os.system('"cd /d E:\\VIDEOS" && youtube-dl -f 43 '+ytplaylink1)
                elif '480' in quality:
                    r=os.system('"cd /d E:\\VIDEOS" && youtube-dl -f 18 '+ytplaylink1)
                elif '720' in quality:
                    r=os.system('"cd /d E:\\VIDEOS" && youtube-dl -f 22 '+ytplaylink1)
                if(r==1):
                    print('THE FORMAT YOU SELECTED NOT FOUND... PELASE SELECT LOWER QUALITY')
                    download()

            download()
        else:
            ysearch(command.replace('youtube',""))

    elif 'joke' in command:
        res = requests.get('https://icanhazdadjoke.com/',headers={"Accept":"application/json"})
        if res.status_code == requests.codes.ok:
            talkToMe(str(res.json()['joke']))
        else:
            talkToMe('hahaha')

    elif 'facts' in command:
        fw = open('D:\\PYTHON\\PROJECT\\.facts.txt',encoding="utf8")
        facts = fw.read()
        facts = facts.split('\n')
        while True:    
            i = random.randrange(0,len(facts)-1)
            #print(facts[i])
            talkToMe(facts[i])
            break

    elif 'quotes' in command:
        fw = open('D:\\PYTHON\\PROJECT\\.quotes.txt','r')
        vocab = fw.read()
        vocab = vocab.split('\n')

        while True:
            i = random.randint(0,2002)
            if i % 2 == 0:
                if len(vocab[i]) < 118:
                    #sendmessage(vocab[i],vocab[i+1])
                    #print(vocab[i]+" said by "+vocab[i+1])
                    talkToMe(vocab[i]+" said by "+vocab[i+1])
                    break
                else:
                    continue
            else:
                continue

    elif 'teach me' in command:
        fw = open('D:\\PYTHON\\PROJECT\\.vocab.txt','r')
        vocab = fw.read()
        vocab = vocab.split('\n')

        while True:
            i = random.randint(0,len(vocab)-1)
            if i % 2 == 0:
                #sendmessage(vocab[i],vocab[i+1])
                print(vocab[i]+"--"+vocab[i+1])
                for j in range(3):
                    talkToMe(vocab[i]+" meaning "+vocab[i+1]+".")
                break
            else:
                continue

    elif 'cricket' in command:
        url = "http://static.cricinfo.com/rss/livescores.xml"
        sc = requests.get(url)
        soup = BeautifulSoup(sc.text,'lxml')

        i = 1
        for data in soup.findAll('item'):
            print(str(i)+'. '+data.find('description').text)
            i += 1
         

        '''for i in range(10):
            url = 'http://www.snapple.com/real-facts/list-view/'+str(i+1)
            print('url:',url)       
            sc = requests.get(url)
            soup = BeautifulSoup(sc.text,'lxml')
            fact = soup.findAll('p',{'class':'fact_detail'})
            print('fact:',fact)
            for i in range(len(fact)):
                fw.write(fact[i].text+'')
        '''

    elif 'email' in command:
        talkToMe('Who is the recipient?')
        recipient = myCommand()

        if 'armaan' in recipient:
            talkToMe('What should I say?')
            content = myCommand()

            #init gmail SMTP
            mail = smtplib.SMTP('smtp.gmail.com', 587)

            #identify to server
            mail.ehlo()

            #encrypt session
            mail.starttls()

            #login
            mail.login('username', 'password')

            #send message`
            mail.sendmail('Arman Khan', '*****@*****.**', content)

            #end mail connection
            mail.close()

            talkToMe('Email sent.')


    elif 'lock'== command:
        subprocess.call('rundll32.exe user32.dll,LockWorkStation')

    elif 'new folder' in command:
        os.system('mkdir ad')

    elif 'new file' in command:
        talkToMe("name of a file?")
        #name=str(myCommand())
        name=str(typeCommand())
        if('python' in command):
            os.system('NUL >'+ name+'.py')
        else:
            os.system('NUL >'+name+'.txt')
        talkToMe("File Created")
 
    elif 'cmd' in command:
        os.system('start "" "C:\\WINDOWS\\system32\\cmd.exe"')

    elif 'take a note' in command:


        f = open('Notes.txt','a')
        t = time.asctime(time.localtime(time.time()))
        f.write('\n'+t+'\n'+command.replace('take a note that',"")) 
        f.close()
        talkToMe("Done")

    elif 'read my notes' in command:
        f = open('Notes.txt','r')
        talkToMe(f.read())
        f.close()

    elif 'clear my notes' in command:
        f = open('Notes.txt','w')
        f.close()
        talkToMe("Done")

    

    elif 'minimise all' in command:
        os.system('nircmd sendkeypress rwin+"d"')

    elif 'maximise all' in command:
        os.system('nircmd sendkeypress rwin+shift+"m"')

    elif 'volume' in command or 'silent' in command or 'mute' in command:
        if 'max' in command or 'full' in command:
            os.system('nircmd.exe mutesysvolume 30000')
        elif 'increase' in command or 'up' in command:
            os.system('nircmd.exe changesysvolume 10000')
        elif 'decrease' in command or 'down' in command:
            os.system('nircmd.exe changesysvolume -10000')
        elif 'silent' in command or 'mute' in command:
            os.system('nircmd.exe mutesysvolume 1')
        else:
            os.system('nircmd.exe mutesysvolume 0')


    elif 'low brightness' in command or 'low light' in command:
        os.system('nircmd.exe setbrightness 5')
    elif 'medium brightness' in command or 'medium light' in command:
        os.system('nircmd.exe setbrightness 50')
    elif 'full brightness' in command or 'max light' in command: 
        os.system('nircmd.exe setbrightness 100')
    elif 'screen of' in command:
        os.system('nircmd.exe monitor off')
    elif 'screen on' in command:
        os.system('nircmd sendkeypress ctrl')
    elif 'empty bin' in command:
        os.system('nircmd.exe emptybin')

    elif 'next song' in command:
        a=str(random.choice(os.listdir("E:\\MUSIC")))
        path = "E:\\MUSIC"+'\\'+a
        os.system(path)

    elif 'song' in command or 'music' in command or 'play' in command:
        print("IN SONG")

        command=command.title()
        command=command.replace('Song',"")
        command=command.replace('Music',"")
        command=command.replace('Play',"")
        for root, dirs,files in os.walk("E:\\MUSIC"):
            for file in files:
                file = file.replace('(',"")
                file = file.replace(')',"")
                # file = file.replace(''," ") 
                # file = file.replace('('," ")
                # file = file.replace('('," ")
                # file = file.replace('('," ")
                if command in file.replace('_',' '):
                    path = "E:\\MUSIC"+'\\'+file
                    os.system('"'+path+'"')
                    break
            else:
                talkToMe("Song Not Found. Do you want me to Download it?")
                if(typeCommand()=='yes'):
                    a2=[]
                    word2 = command.replace('play',"")
                    word2 = command.replace('song',"")
                    word2 = word2+' lyrics'
                    url2 = 'https://www.youtube.com/results?search_query=+'+word2
                    yt2='https://www.youtube.com'
                    #webbrowser.open_new_tab(url)
                    class MyOpener2(FancyURLopener):
                        version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'   # Set this to a string you want for your user agent

                    myopener2 = MyOpener2()
                    page2 = myopener2.open(url2).read()
                    webpage2 = page2.decode('utf-8')

                    soup2 = bs.BeautifulSoup(webpage2,'lxml')

                    div2 = soup2.body
                    for data2 in div2.find_all(href=True):
                        a2.append(data2.get('href'))

                        #print(a)

                    matching2 = [s2 for s2 in a2 if '/watch?' in s2]
                    asa2 =matching2[0]
                    asa2 = asa2.replace('/watch?v=','')
                    print(asa2)
                    # webbrowser.open(DLlink)

                    ytplaylink2 = yt2+matching2[0]
                    print(ytplaylink2)
                    word2 = word2.replace(" ","_")
                    word2 = '1_'+word2
                    os.system('"cd /d E:\\MUSIC" && youtube-dl --output '+word2+'.%(ext)s -i --extract-audio --audio-format mp3 --audio-quality 0 '+ytplaylink2)
                    #webbrowser.open_new_tab(ytplaylink)
                else:
                    talkToMe("Ok, ask me something else.")

    elif 'music' in command or 'song' in command or 'play' in command:
        a=str(random.choice(os.listdir("E:\\MUSIC")))
        path = "E:\\MUSIC"+'\\'+a
        os.system(path)

    

        #if 'video' in command:
         #   command=command.title()




    elif 'stop music'in command:
        os.system('nircmd.exe killprocess wmplayer.exe')

    elif 'task manager' in command:
        os.system('nircmd sendkeypress ctrl+shift+esc')

    elif 'clipboard' in command or 'clip board' in command:
        talkToMe(clipboard.paste())

    elif 'calculate' in command:

        value = command.replace("what's ", "")
        value = command.replace("calculate","")
        value = value.replace(" times", "*")
        value = value.replace(" plus", "+")
        value = value.replace(" minus", "-")
        value = value.replace(" divides", "/")
        value = value.replace(" divide", "/")
        value = value.replace(" x", "*")
        print(value)

        try:
            
            finalValue = eval(value)
            #print(finalValue)
            #eval(finalValue)
            talkToMe(finalValue)
                

        except:
            try:
                client = wolframalpha.Client("4E3H79-A3ARKHYKU9")
                #print('command:',command)
                res = client.query(command)
                answer = next(res.results).text
                #print(answer)

                #print("IN WIKI")
                talkToMe(answer)
            except:
                talkToMe("I don't Understand")

    elif 'current temperature' in command:
        owm = pyowm.OWM('3b8dc8474c4fdddfea2631f41f134a97')  
        obs = owm.weather_at_place("Mumbai,in")  
        temperature=obs.get_weather().get_temperature('celsius')
        talkToMe("The temperature is "+str(temperature['temp_max'])+" degree celsius")

    elif 'change wallpaper' in command:
        a=str(random.choice(os.listdir("C:\\Users\\HP-Probook\\Downloads")))
        print('a',a)
        pic_path = "C:\\Users\\HP-Probook\\Downloads"+'\\'+a
        print('pic_path',pic_path)
        cmd = 'REG ADD \"HKCU\\Control Panel\\Desktop\" /v Wallpaper /t REG_SZ /d \"%s\" /f' %pic_path
        os.system(cmd)
        os.system('rundll32.exe user32.dll, UpdatePerUserSystemParameters')
        os.system('rundll32.exe user32.dll, UpdatePerUserSystemParameters')
        print('Wallpaper is set.')


    # elif 'open' in command:
    #     #command = 'open notepad'
    #     command = command.replace('open',"")
    #     command = command.replace(" ","")
        
    #     os.system('nircmd sendkeypress rwin')
    #     for i in command:
    #         os.system('nircmd sendkeypress '+i)
    #     os.system('nircmd sendkeypress enter')

    elif 'news' in command:
        req = Request('https://www.google.com/search?q=news&client=firefox-b-ab&source=lnms&tbm=nws&sa=X&ved=0ahUKEwiwo5iM-pHaAhUIqo8KHSlQBbwQ_AUIDCgD&biw=1366&bih=654', headers={'User-Agent': 'Mozilla/5.0'})

        web_byte = urlopen(req).read()
        webpage = web_byte.decode('utf-8')

        soup = bs.BeautifulSoup(webpage,'lxml')

        div = soup.body

        for data in div.find_all('h3'):
            news=data.text
            print(news)

    elif (command==""):
        assistant(typeCommand())
            
            

    else:
        request = ai.text_request()
        request.query = command
        response = request.getresponse().read()
        output = json.loads(response)
        answer = output["result"]["fulfillment"]["speech"]
        #talkToMe(answer)
        if(answer=="" or answer=="not found"):

            talkToMe("What "+command+"? "+"do you want me to search deeply?")
            #if(myCommand()=='yes'):
            if(typeCommand()=="yes"):
                try:
                    client = wolframalpha.Client("4E3H79-A3ARKHYKU9")
                    #print('command:',command)
                    res = client.query(command)
                    answer = next(res.results).text
                    #print(answer)

                    #print("IN WIKI")
                    talkToMe(answer)
                    #talkToMe("improve your internet speed")

                except:

                    try:
                        #print(wikipedia.summary(command))
                        
                        print("IN WIKI")
                        talkToMe(wikipedia.summary(command))
                        #talkToMe("improve your internet speed")
                    except:
                        talkToMe("Even internet has no answer about it.")
            else:
                talkToMe("OK, ask me some thing else")

        else:
            talkToMe(answer)
Esempio n. 10
0
import imdb

mov = imdb.IMDb()
print()
a=input("Enter Movie name: ")
movie = mov.search_movie(a)
id = movie[0].getID()
movies = mov.get_movie(id)
name = movies['title']
year = movies['year']
rate = movies['rating']
direct = movies['directors']
casting = movies['cast']

print('Movie Info:- ')
print()
print(f'{name} - {year}')
print(f'Rating: {rate}')
directStr = '\n'.join(map(str, direct))
print(f'Directors: {directStr}')
actors = '\n'.join(map(str, casting))
print(f'Actors: \n{actors}')
Esempio n. 11
0
Usage: get_person.py 'personID'

NOTES:
- this script is python2 on purpose because the imdb module is currently only available for python2 in ubuntu.
"""

import sys

import imdb

if len(sys.argv) != 2:
    print('{0}: usage: {0} [personID]'.format(sys.argv[0]))
    print('{0}: usage: {0} 0124930'.format(sys.argv[0]))
    print('{0}: usage: {0} 0000264 (for unicode)'.format(sys.argv[0]))
    sys.exit(1)

personID = sys.argv[1]
connection = imdb.IMDb()
out_encoding = sys.stdout.encoding or sys.getdefaultencoding()

person = connection.get_person(personID)

i_canonical_name = person['canonical name']
print('i_canonical_name is [{0}]'.format(
    i_canonical_name.encode(out_encoding)))

for k, v in person.items():
    if isinstance(v, unicode):
        v = v.encode(out_encoding)
    print('[{0}],[{1}]'.format(k, v))
Esempio n. 12
0
import os
import imdb
import winshell
from imdbpie import Imdb
from win32com.client import Dispatch

ib = imdb.IMDb()

# Import the imdb package.
ia = Imdb()

del_ext = ["txt" "nfo" "png" "jpg" "url"]
ign_ext = ["exe" "zip" "part"]
ign_key = []

# res = ia.search_for_title('Deadpool')
# genre = ia.get_title_genres(res[0]['imdb_id'])
# print(genre['genres'])

base = "F:\Ripped\Movies"
os.chdir(base)
for root, subdirs, files in os.walk(os.getcwd()):
    for f in files:
        if root == base:
            continue
        if any(ext == f[:(-1 * len(ext))] for ext in ign_ext):
            continue
        if any(ext == f[:(-1 * len(ext))] for ext in del_ext):
            os.remove(os.path.join(root, f))

        movie = '.'.join(f.split('.')[:-1]).split(")")[0] + ")"
Esempio n. 13
0
from urllib.error import URLError
import os, errno
import requests
from lxml import html
import imdb
import re
import shelve
import sys
import itertools
from Media_Portal import global_params
if os.name == 'nt':
    import win32api

VIDEO_FORMATS = ('.mp4', '.avi', '.mkv', '.flv')
MOVIE_MIN_SIZE = 200 * 1024 * 1024
access = imdb.IMDb()

try:
    os.makedirs(global_params.BASEPATH)
except OSError as e:
    if e.errno != errno.EEXIST:
        raise

shelffile1 = shelve.open(global_params.MOVIEDATA_FILE)
shelffile2 = shelve.open(global_params.PATHS_FILE)
shelffile3 = shelve.open(global_params.FILENAMES_FILE)

if 'Movies' not in list(shelffile1.keys()):
    shelffile1['Movies'] = list()
if 'Paths' not in list(shelffile2.keys()):
    shelffile2['Paths'] = list()
Esempio n. 14
0
def getShowDetails(show_name, netflix_id):
    """ given a show's name, a dictionary of 
    - imdb_id,
    - netflix_id,
    - title,
    - genres
    - language
    - rating
    - votes
    - plot_outline
    - year
    - kind
    - directors
    - writers //
    - cast
    - plot
    - full-size cover url
    will be returned """

    # uses imdb

    # show = sdb.get_movie(sdb.search_movie("3 idiots")[0].getID())
    found = True
    details = {}

    showDB = imdb.IMDb()
    show_from_search = showDB.search_movie(show_name)
    if len(show_from_search)==0:
        return (False, details)


    imdb_id = show_from_search[0].getID()
    show = showDB.get_movie(imdb_id)



    if 'title' in show:
        title = show['title']
    else:
        title = show_name

    if 'genres' in show:
        genres = show['genres'][:5]
    else:
        genres = ['N/A']

    if 'languages' in show:
        language = show['languages'][0]
    else:
        language = 'N/A'

    if 'rating' in show:
        rating = str(show['rating'])
    else:
        rating = 'N/A'

    if 'votes' in show:
        votes = str(show['votes'])
    else:
        votes = 'N/A'


    if 'year' in show:
        year = str(show['year'])
    else:
        year = 'N/A'

    if 'kind' in show:
        kind = show['kind']
    else:
        kind = 'N/A'

    if 'directors' in show:
        directors = [d['name'] for d in show['directors']][:2]
    else:
        directors = ['N/A']

    # if 'writers' in show:
    #     writers = [w['name'] for w in show['writers']][:2]
    # else:
    #     writers = ['N/A']

    if 'cast' in show:
        cast = [c['name'] for c in show['cast']][:5]
    else:
        cast = ['N/A']

    if 'plot' in show:
        plots = show['plot']
        plots_len = [len(p) for p in plots]
        plot = plots[plots_len.index(max(plots_len))]
    else:
        plot = 'N/A'

    if 'plot outline' in show:
        plot_outline = show['plot outline']
    else:
        plot_outline = plot

    r = random.randint(400, 600)
    plot_outline = plot_outline[:r] + ".."

    cover_url = show.get('full-size cover url')
    if not cover_url:
        cover_url = ''


    details['imdb_id'] = imdb_id
    details['netflix_id'] = netflix_id
    details['title'] = title
    details['genres'] = genres
    details['language'] = language
    details['rating'] = rating
    details['votes'] = votes
    details['plot_outline'] = plot_outline
    details['kind'] = kind
    details['year'] = year
    details['directors'] = directors
    # details['writers'] = writers
    details['cast'] = cast
    details['plot'] = plot
    details['cover_url'] = cover_url


    # make markdowns with the details
    createMarkdownPost(details)
    # save the image
    if cover_url!='':
        saveImg(cover_url, imdb_id)

    return (found, details)

# ['cast', 'genres', 'runtimes', 'countries', 'country codes', 'language codes', 'color info', 'aspect ratio', 'sound mix'
# , 'box office', 'certificates', 'original air date', 'rating', 'votes', 'cover url', 'plot outline', 'languages', 'title
# ', 'year', 'kind', 'directors', 'writers', 'producers', 'composers', 'cinematographers', 'editors', 'editorial departmen
# t', 'casting directors', 'production designers', 'art directors', 'set decorators', 'costume designers', 'make up depart
# ment', 'production managers', 'assistant directors', 'art department', 'sound department', 'special effects', 'visual ef
# fects', 'stunts', 'camera department', 'animation department', 'casting department', 'costume departmen', 'location mana
# gement', 'music department', 'script department', 'transportation department', 'miscellaneous', 'thanks', 'akas', 'write
# r', 'director', 'production companies', 'distributors', 'special effects companies', 'other companies', 'plot', 'synopsi
# s', 'canonical title', 'long imdb title', 'long imdb canonical title', 'smart canonical title', 'smart long imdb canonic
# al title', 'full-size cover url']



# getShowDetails("The Woods", "81108061")
import imdb
import pandas as pd

from itertools import chain
from collections import Counter

IA = imdb.IMDb()

import spacy

NLP = spacy.load("en_core_web_sm")

from spacy.lang.en.stop_words import STOP_WORDS

from fuzzywuzzy import fuzz
from fuzzywuzzy import process

from textblob import TextBlob
import time

NOT_USEFUL_NOUNS = set()
NOT_USEFUL_NOUNS.add("the golden globes")
NOT_USEFUL_NOUNS.add("golden globes")
NOT_USEFUL_NOUNS.add("goldenglobes")
NOT_USEFUL_NOUNS.add("golden globe")
NOT_USEFUL_NOUNS.add("the golden globe")
NOT_USEFUL_NOUNS.add("rt")
NOT_USEFUL_NOUNS.add("amp")
NOT_USEFUL_NOUNS.add("a motion picture")
NOT_USEFUL_NOUNS.add("drama")
NOT_USEFUL_NOUNS.add("comedy")
import imdb

moviesDB = imdb.IMDb()
movies = moviesDB.search_movie('The Shawshank Redemption')
id = movies[0].getID()
movie = moviesDB.get_movie(id)
title = movie['title']
year = movie['year']
rating = movie['rating']
directors = movie['directors']
casting = movie['cast']
print('film bilgileri;')
print(f'{title} - {year}')
print(f'Oran: {rating}')
direcStr = ' '.join(map(str, directors))
print(f'Yönetmenler: {direcStr}')
actors = ' '.join(map(str, casting[0:5]))
print(f'Oyuncular: {actors}')
print('made by falcon excalibur(can cayar)')
    def searchMovies(self):
        """Search from imdb movie database"""
        result_list = {}
        query_string = self.newQuery

        if query_string != "":
            counter = 1
            counter_max = int(self.nbr_results)
            result_id = 0
            result_artist = []

            self.controlArea.setDisabled(True)

            # Initialize progress bar
            progressBar = ProgressBar(self, iterations=counter_max)

            ia = imdb.IMDb()

            # movie name
            name = query_string

            # searching the movie
            search = ia.search_movie(name)
            print(search)

            # Each result is stored in a dictionnary with its title
            # and year of publication if it is specified
            for result in search:
                if counter <= counter_max:
                    #print(counter)
                    #print(counter_max)
                    try:
                        result_id += 1
                        year = result['year']
                        movie_id = result.movieID
                        result_list[result_id] = {
                            'name': result,
                            'year': year,
                            'id': movie_id
                        }
                    except KeyError:
                        result_id += 1
                        result_list[result_id] = {
                            'name': result,
                        }

                    counter += 1
                else:
                    break

            # 1 tick on the progress bar of the widget
            progressBar.advance()
            # Stored the results list in the "result_list" variable
            self.searchResults = result_list

            # Reset and clear the visible widget list
            del self.titleLabels[:]

            # Update the results list with the search results
            # in order to display them
            for idx in self.searchResults:
                try:
                    result_string = f'{self.searchResults[idx]["name"]} - {self.searchResults[idx]["year"]}'
                    self.titleLabels.append(result_string)
                except KeyError:
                    result_string = f'{self.searchResults[idx]["name"]}'
                    self.titleLabels.append(result_string)

            self.titleLabels = self.titleLabels
            self.clearButton.setDisabled(False)
            self.addButton.setDisabled(False)

            # Clear progress bar.
            progressBar.finish()
            self.controlArea.setDisabled(False)

        else:
            self.infoBox.setText("Please enter a movie title", "warning")
Esempio n. 18
0
 def __init__(self):
   self.cache = ImdbAPI.load(self)
   self.top_250 = ImdbAPI.read_top_250(self)
   if imdb is not None: self.imdb = imdb.IMDb()
Esempio n. 19
0
from discord.ext import commands
import imdb
import mysql.connector
from dotenv import load_dotenv

load_dotenv()

mydb = mysql.connector.connect(
    host=os.environ["host"],
    user=os.environ["user"],
    password=os.environ["password"],
    database="movies",
)
mycursor = mydb.cursor()

movies = imdb.IMDb()


async def add_suggestion(id, name, suggester):
    sql = "INSERT INTO suggestions (id,name,suggester) VALUES (%s, %s, %s)"
    val = (int(id), name, suggester)
    mycursor.execute(sql, val)

    mydb.commit()


class Movies(commands.Cog):
    """
    Handles the movie night tracking functionality
    """
    def __init__(self, bot):
Esempio n. 20
0
def getTitles(path, newpath):

    titles = []

    db = False
    if (os.path.exists("titles.p")):
        titles = pickle.load(open("titles.p", "rb"))
        db = True
    ia = imdb.IMDb()
    d = enchant.Dict("en_US")

    for film in os.listdir(path):

        if (db):
            for name in titles:
                if (name == film):
                    continue

        else:
            movie_name = film
            movie_name = strip_patterns(movie_name)
            movie_name = movie_name.strip()

            movie_name = movie_name.replace('.', ' ')
            movie_name = movie_name.replace(',', '')
            if (not movie_name.isupper()):
                movie_name = re.sub(r"(\w)([A-Z])", r"\1 \2", movie_name)

            movie_name = re.sub(r'^https?:\/\/.*[\r\n]*',
                                '',
                                movie_name,
                                flags=re.MULTILINE)
            print("file:", movie_name)
            movie_name = movie_name.split()
            #print("split:", movie_name, "\n")
            pot_name = str()
            #store first possible
            first = str()
            for word in movie_name:
                if (d.check(word)):

                    if (pot_name == ""):
                        pot_name = word
                    else:
                        pot_name = pot_name + " " + word
                #pot_name.join(word)
                    if not ia.search_movie(pot_name):
                        break
                    result = str(ia.search_movie(pot_name)[0])
                    result = result.replace('.', ' ')
                    result = result.replace(',', '')
                    #print("potential:", pot_name)
                    #print("result:" ,result)
                    lw_r = result.lower()
                    lw_p = pot_name.lower()
                    if (first != "" and lw_r == lw_p):
                        #print("1")
                        first = result
                        #print("new first is", first, "\n")

        ##            elif(first!="" and lw_r.find(lw_p)):
        ##                print("2")
        ##                first = result
        ##                print("name is", first, "\n")
        ##
                    if (first == "" and lw_r == lw_p):
                        #print("3")
                        first = result
                        #print("first: ", first)
                else:
                    bad_words.append(word)
            if (first == ""):
                print("Unsure film title")
                print("Original: ", film)
                print("new: ", result)
                choice = input(str("Is this okay? y/n "))
                if (choice == "y"):
                    title = result

                else:
                    title = input(str("Input title: "))

        #print("4")
            else:
                title = first
                print("result", title, "\n")

            if (os.path.exists(os.path.join(newpath, title))):
                print("file already exists")
                print("title: ", title)
                print("original file name:", film)
                title = input(str("new name: "))
            if (os.path.isfile(film)):
                os.mkdir(os.path.join(newpath, title))
                shutil.move(film, os.path.join(newpath, title))
                print(film, "has been added to new directory: ",
                      os.path.join(newpath, title))
            else:
                os.rename(os.path.join(path, film),
                          os.path.join(newpath, title))
            titles.append(title)

    pickle.dump(titles, open("titles.p", "wb"))
    pickle.dump(bad_words, open("bad_words.p", "wb"))
Esempio n. 21
0

def genresString(genres=None):

    jsonGenres = json.loads(genres)
    #print(jsonGenres)
    returnString = ""
    for x in jsonGenres:
        #print (x['name'])
        returnString = returnString + " " + x['name']
    return returnString


if __name__ == "__main__":

    ia = imdb.IMDb()  # by default access the web.

    # Search for a movie (get a list of Movie objects).
    s_result = ia.search_movie('Star')

    #print(s_result)
    # Print the long imdb canonical title and movieID of the results.
    #for item in s_result:
    #    print(item['long imdb canonical title'], item['year'], item.movieID)

    #sys.exit(0)

    Session = sqlalchemy.orm.sessionmaker(db)
    session = Session()

    base.metadata.create_all(db)
Esempio n. 22
0
def align_movie_info(type):
    movie_to_info = {}
    db = imdb.IMDb()
    found_id = 0
    found_dia = 0

    if type == 'walker' or type == 'w':
        walker_raw = './data/walker2015_raw/'
        for genre in os.listdir(walker_raw):
            if genre != '.DS_Store':
                print('On walker genre:', genre)
                genre_path = walker_raw + genre + '/'
                for raw_file in os.listdir(genre_path):
                    raw_file_path = genre_path + raw_file
                    dialog_file_path = get_walker_diag(raw_file_path)
                    if DEBUGGING: print('Dialog path:', dialog_file_path)

                    if dialog_file_path is not None:
                        found_dia += 1
                        info = {'source': 'walker', 'title': None, 'id': None}
                        title = find_walker_title(raw_file_path)
                        if DEBUGGING: print('Found title:', title)

                        if title is not None:
                            info['title'] = title
                            char_doc = parse_walker_chars(dialog_file_path)
                            if DEBUGGING: print('Parsed characters:', char_doc)

                            imdb_id = match_id(db, title, char_doc)
                            if DEBUGGING: print('Aligned id:', imdb_id)

                            if imdb_id is not None:
                                found_id += 1
                                info['id'] = imdb_id
                        movie_to_info[dialog_file_path] = info
                        print(dialog_file_path, info)
            pickle.dump(movie_to_info, open('walker_alignments.p', 'wb'))

    if type == 'agarwal' or type == 'a':
        agarwal_path = './data/agarwal2015_screenplays/'
        for dir in os.listdir(agarwal_path):
            if dir != '.DS_Store':
                print('Agarwal dir:', dir)
                dir_path = agarwal_path + dir + '/'

                for file in os.listdir(dir_path):
                    found_dia += 1
                    file_path = dir_path + file
                    if DEBUGGING: print('File_path:', file_path)

                    info = {'source': 'agarwal', 'title': None, 'id': None}
                    title = find_agarwal_title(file_path)
                    info['title'] = title
                    if DEBUGGING: print('Title:', title)

                    char_count, char_doc = parse_agarwal_chars(file_path)
                    if DEBUGGING:
                        print('Char count:', char_count, 'Chars:', char_doc)

                    if char_count > 5:
                        imdb_id = match_id(db, title, char_doc)
                        if imdb_id is not None:
                            found_id += 1
                            info['id'] = imdb_id

                    movie_to_info[file_path] = info
                    print(found_dia, file_path, info)
            pickle.dump(movie_to_info, open('agarwal_alignments.p', 'wb'))

    elif type == 'gorinski' or type == 'g':
        gorinski_path = './data/gorinski/'
        for dir in os.listdir(gorinski_path):
            if dir != '.DS_Store':
                print('Gorinski dir:', dir)
                dir_path = gorinski_path + dir + '/'

                for movie_folder in os.listdir(dir_path):
                    if movie_folder != '.DS_Store':
                        found_dia += 1
                        file_path = dir_path + movie_folder + '/script_clean.txt'
                        if DEBUGGING: print('File_path:', file_path)

                        info = {
                            'source': 'gorinski',
                            'title': None,
                            'id': None
                        }
                        title = find_gorinski_title(movie_folder)
                        info['title'] = title
                        if DEBUGGING: print('Title:', title)

                        char_count, char_doc = parse_gorinski_chars(file_path)
                        if DEBUGGING:
                            print('Char count:', char_count, 'Chars:',
                                  char_doc)

                        if char_count > 5:
                            imdb_id = match_id(db, title, char_doc)
                            if imdb_id is not None:
                                found_id += 1
                                info['id'] = imdb_id

                        movie_to_info[file_path] = info
                        print(found_dia, file_path, info)
            pickle.dump(movie_to_info, open('gorinski_alignments.p', 'wb'))

    print('Found {} dialog files, found {} ids'.format(found_dia, found_id))
Esempio n. 23
0
# -*- coding: utf-8 -*-

import logging
import string
from .helpers import check_imdb, imdb2number

import imdb as imdbapi

logger = logging.getLogger(__name__)

_imdb = imdbapi.IMDb()


def search_episode(series, season, episode, guess_series_imdb_id=None):
    results = dict()
    logger.debug('Use imdb.org to get imdbID of {} {:d}x{:d}'.format(
        series, season, episode))

    guess_series_imdb_id = imdb2number(guess_series_imdb_id)
    if not guess_series_imdb_id:
        return results

    try:
        show_imdb = _imdb.get_movie_episodes(guess_series_imdb_id).get(
            'data', dict()).get('episodes', dict())
        episode_imdb = show_imdb[season][episode]
        results['episode_imdb_id'] = check_imdb(episode_imdb.getID())
        logger.debug('Found ids: {}'.format(results))
    except Exception:
        logger.exception(
            'Could not find exact match on imdb.com for show {}, episode {:d}x{:d}'
Esempio n. 24
0
import imdb
hr = imdb.IMDb()

print("Welcome to the Movie Search\n")
movie_name = input("Enter movie name: ")

movies = hr.search_movie(str(movie_name))

index = movies[0].getID()

movie = hr.get_movie(index)

title = movie['title']
year = movie['year']
cast = movie['cast']

list_of_cast = ','.join(map(str, cast))

print("Title :", title)
print("Year :", year)
print("Cast :", list_of_cast)
Esempio n. 25
0
import imdb
import synonyms as sy

ia = imdb.IMDb()  # Initializes the IMDb integration through an IMDbPy method


def findMovie(userName):  # Finds the movie requested by the user
    print('IMDBot: Which movie would you like to know about?')
    search = input(f'{userName}: ')
    movie = searchForMovie(userName, search)
    if movie == '':
        print(f'IMDBot: Ok. What else can I help you with?')
        return ''
    else:
        title = movie['title']
        print(f'IMDBot: Ok! What do you want to know about {title}?'
              )  # confirms the movie
        return movie  # returns movie object


def searchForMovie(userName, search):
    searchID = 0  #an index to go through the list to confirm the movie the user is talking about
    print('IMDBot: Ok! Let me see if I can find it...'
          )  # Serves to provide a buffer while the query is sent
    while True:
        try:
            if (searchID > 0 and searchID % 3 == 0
                    and askToContinue(userName) == False):
                return ''
            else:
                movie = ia.get_movie(
Esempio n. 26
0
import os
import logging
import random
import json
import urllib2
from bson.objectid import ObjectId

import tornado.ioloop
import tornado.web
import tornado.autoreload

from rottentomatoes import RT
import imdb
from pymongo import MongoClient

imd = imdb.IMDb()
rt = RT()
client = MongoClient()
db = client.mydb


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("home.html", title='title')


class GameHandler(tornado.web.RequestHandler):
    def get(self):
        players = create_player_dict(self.get_argument('players'))
        game_id = start_game_session(players)
Esempio n. 27
0
import imdb
from colorama import Fore

app = imdb.IMDb()
movie = "war"
results = app.search_movie(movie, results=10)
first = results[0]
data = first.movieID
print(first.movieID)

print(app.get_movie(first.movieID))

print(data['year'])
Esempio n. 28
0
def get_imdb(list, scan_method):
    ''' Get IMDB data. '''

    if not list:
        return

    i = imdb.IMDb()

    # Traverse through all files
    for item in list:
        folder = item['folder']
        keywords = item['keywords']

        # search imdb
        in_encoding = sys.stdin.encoding or sys.getdefaultencoding()
        out_encoding = sys.stdout.encoding or sys.getdefaultencoding()

        if verbose_level > 1:
            print "Folder: " + folder
            print "Keywords: " + keywords

        if use_dic == 1:
            keywords = spellcheck(keywords)
            if verbose_level > 0:
                print "Keywords: " + keywords

        title = unicode(keywords, in_encoding, 'replace')
        try:
            # Do the search, and get the results (a list of Movie objects).
            results = i.search_movie(title, limit)
        except imdb.IMDbError, e:
            print "Probably you're not connected to Internet.  Complete error report:"
            sys.exit(3)

        if results:
            # Print the results.
            if verbose_level > 4:
                print '%s result%s for "%s":' % (len(results),
                                                 ('', 's')[len(results) != 1],
                                                 title.encode(
                                                     out_encoding, 'replace'))
                print 'movieID\t: imdbID : title'

            # Print the long imdb title for every movie.
            if verbose_level > 2:
                for movie in results:
                    outp = u'%s\t: %s : %s' % (movie.movieID,
                                               i.get_imdbID(movie),
                                               movie['long imdb title'])
                    print outp.encode(out_encoding, 'replace')

            #get close matches only example
            #words = ['hello', 'Hallo', 'hi', 'house', 'key', 'screen', 'hallo', 'question', 'format']
            #difflib.get_close_matches('Hello', words)

            # Use first result
            movie = results[0]

            i.update(movie)
            movieID = movie.movieID

            # print movie info
            filmInfo = movie.summary() + '\n'
            filmInfo += u'IMDB ID: %s.\n' % movieID

            # save covers
            thumb_url = movie.get('cover url')
            cover_url = movie.get('full-size cover url')

            if cover_url:
                filmInfo += u'Cover: %s.\n' % cover_url + '\n'
                print 'Fetching cover'
                try:
                    # Fetch online image
                    if (not os.path.isfile(folder + "/thumb.jpg")
                            or scan_method == 'all'):
                        urllib.urlretrieve(thumb_url, folder + "/thumb.jpg")
                    if (not os.path.isfile(folder + "/folder.jpg")
                            or scan_method == 'all'):
                        urllib.urlretrieve(cover_url, folder + "/folder.jpg")
                except imdb.IMDbError, e:
                    print "NOTICE: Could not download cover:"
            else:
                print 'NOTICE: No cover available'

            # Write film info
            write_info(folder, filmInfo.encode(out_encoding, 'replace'))

            if verbose_level > 0:
                print 'Sending to CMS'
            send_cms(folder, movie)
    return genres


print("From TMDB: The genres of the movie are: ",
      get_movie_genres_tmdb("The Matrix"))
print(
    "All the Movie information from TMDB gets stored in a dictionary with the following keys for easy access -"
)
print(info.keys())
info = get_movie_info_tmdb("The Matrix")
print("From TMDB: ", info['tagline'])

#===============================IMDB Stuff down below================================================

# Create the IMDB object that will be used to access the IMDb's database.
imbd_object = imdb.IMDb()  # by default access the web.

# Search for a movie (get a list of Movie objects).
results = imbd_object.search_movie('The Matrix')

# As this returns a list of all movies containing the word "The Matrix", we pick the first element
movie = results[0]

imbd_object.update(movie)

print("All the information we can get about this movie from IMDB-")
print(movie.keys())
print("From IMDB: The genres of the movie are: ", movie['genres'])

#========================Obtaining Top 20 Movies from TMDB==========================================
def getlanguagecodes(self):
    ia = imdb.IMDb()
    m = ia.get_movie(ia.search_movie(self)[0].getID())
    print(m["language codes"])