renix1

fetch data of programs of tv

Jan 25th, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.51 KB | None | 0 0
  1. # coding: utf-8
  2.  
  3. import requests
  4. import json
  5. import shutil
  6. import os
  7. import glob
  8. import sys
  9. import multiprocessing as mp
  10.  
  11. """
  12.    TRANSLATOR USED: https://translate.yandex.com/?
  13.    DATABASE MOVIES USED: http://omdbapi.com/
  14. """
  15.  
  16. cabecalho = {'User-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
  17. key = "trnsl.1.1.20170125T181407Z.a7a266350d888956.929a9a628283b699b48ec678da47707fc4d18d6a"
  18.  
  19. def requisicao(titulo, tipo='movies', ano=None):
  20.     data = {'t' : titulo, 'y' : ano, 'type' : tipo}
  21.     try:
  22.         req = requests.get("http://omdbapi.com/",
  23.                             headers=cabecalho,
  24.                             params=data)
  25.         dicionario = json.loads(req.text)
  26.         return dicionario
  27.  
  28.     except Exception as e:
  29.         print(e)
  30.         exit(0)
  31.  
  32.  
  33. def traduzir(texto, dest='pt'):
  34.     data = {'key' : key, 'text': texto, 'lang': dest, 'format' : 'plain'}
  35.     try:
  36.         req = requests.get("https://translate.yandex.net/api/v1.5/tr.json/translate",
  37.                             headers=cabecalho,
  38.                             params=data)
  39.         traduzido = req.text
  40.         resumo = traduzido[traduzido.find('[')+2:traduzido.find(']')-1:]
  41.         return resumo
  42.     except Exception as e:
  43.         print(e)
  44.         exit(0)
  45.  
  46.  
  47. def detalhes(tv):
  48.     resumo = traduzir(tv['Plot']).replace('\\', '')
  49.     print(' FETCHING DATA '.center(80, '-'))
  50.     print("Título: %s (inglês)/%s (português, tradutoção via yandex translator)\n" % (tv['Title'], traduzir(tv['Title'])))
  51.     if tv['Type'] == 'movies':
  52.         print("Ano: %s\n" % tv['Year'])
  53.     else:
  54.         print("Lançamento em %s\n" % tv['Released'])
  55.     print("Diretor: %s\n" % tv['Director'])
  56.     print("Atores: %s\n" % tv['Actors'])
  57.     print("Nota: %s (Metascore, max 100)\n" % tv['Metascore'])
  58.     print("Nota: %s (imdb, max 10)\n" % tv['imdbRating'])
  59.     print("Plot: %s (inglês)\n\nResumo: %s (português, tradução via yandex translator)\n" % (tv['Plot'], resumo))
  60.     if tv['Type'] == 'movies':
  61.         print("Duração: %s\n" % tv['Runtime'])
  62.     else:
  63.         print("Duração (média) por episódio: %s\n" % tv['Runtime'])
  64.     print("Gênero: %s/%s (português, tradução via yandex translator)\n" % (tv['Genre'], traduzir(tv['Genre'])))
  65.     if tv['Type'] == 'series':
  66.         print("Temporadas: %s\n" % tv['totalSeasons'])
  67.     print(' DATA FETCHED '.center(80, '-'))
  68.  
  69.  
  70. def create_folder():
  71.         if os.path.exists('posters/'):
  72.             pass
  73.         else:
  74.             os.mkdir('posters')
  75.         return 'posters/'
  76.  
  77.  
  78. def baixar_poster(url, title):
  79.     if url != "N/A":
  80.         fname = '%s.png' % title.replace(' ', '').replace(':', '')
  81.         directory = create_folder()
  82.         os.chdir(directory)
  83.         if os.path.exists(fname):
  84.             print(" Image is already downloaded ".center(80, '*'))
  85.             if sys.platform.startswith("win32"):
  86.                 os.startfile(os.getcwd()+'\\'+fname)
  87.             else:
  88.                 os.system('shotwell %s&' % os.getcwd()+"//"+fname)
  89.         elif not os.path.exists(fname):
  90.             image = requests.get(url, stream=True)
  91.             print(" Downloading image... ".center(80, '*'))
  92.             with open(fname, 'wb') as outfile:
  93.                 shutil.copyfileobj(image.raw, outfile)
  94.             if sys.platform.startswith("win32"):
  95.                 os.startfile(os.getcwd()+'\\'+fname)
  96.             else:
  97.                 os.system('shotwell %s&' % os.getcwd()+'//'+fname)
  98.             print(" Opening image ".center(80, '*'))
  99.     else:
  100.         print(" IMAGE NOT FOUND ".center(80, '*'))
  101.  
  102.  
  103. def kill_visualizar():
  104.     print(' Closing application '.center(80, 'X'))
  105.     os.system('taskkill /IM dllhost.exe>nul 2>&1')
  106.  
  107.  
  108. def delete_posters(ask='N'):
  109.     if ask == 'S':
  110.         kill_visualizar()
  111.         if sys.platform.startswith("win32"):
  112.             os.chdir(os.getcwd()+'\\posters')
  113.         else:
  114.             os.chdir(os.getcwd()+"//posters")
  115.         files = glob.glob('*.png')
  116.         for file in files:
  117.             os.remove(file)
  118.         print(" Posters removed! ".center(80, 'X'))
  119.     else:
  120.         kill_visualizar()
  121.  
  122.  
  123. def main():
  124.     print(" USER INPUT ".center(80, '~'))
  125.     titulo = str(input('Título: '))
  126.     tipo = str(input("Tipo (série/filme): ")).lower()
  127.     if (tipo == 'série') or (tipo == 'serie'):
  128.         tipo = 'series'
  129.     else:
  130.         tipo = 'movies'
  131.     ano = str(input("Ano do filme: "))
  132.     print(" USER INPUT ".center(80, '~'))
  133.     tv = requisicao(titulo, ano)
  134.     print("REQUESTING", end='')
  135.     for i in range(0, 15, 1):
  136.         for i in range(0, 150000, 1):
  137.             i += 5
  138.         sys.stdout.flush()
  139.         sys.stdout.write('.')
  140.     print('')
  141.     if tv['Response'] == 'True':
  142.         th = mp.Process(target=detalhes, args=(tv,))
  143.         th.start()
  144.         th.join()
  145.         th2 = mp.Process(target=baixar_poster, args=(tv['Poster'], tv['Title']))
  146.         th2.start()
  147.         th2.join()
  148.     else:
  149.         print(" [ * ] %s não encontrado" % tv['Title'])
  150.  
  151.  
  152. if __name__ == "__main__":
  153.     print('')
  154.     print(" DATABASE MULTIMEDIA (Created by Reni A. Dantas) ".center(80, ' '))
  155.     while 1:
  156.         main()
  157.         print(" USER INPUT ".center(80, '~'))
  158.         deseja = input("Deseja sair? (S/n) ").title()
  159.         if deseja == 'S':
  160.             deseja_del = input("Deseja deletar todos os posters? (S/n) ").title()
  161.             delete_posters(deseja_del)
  162.             quit(0)
  163.         print(" USER INPUT ".center(80, '~'))
  164.         kill_visualizar()
Advertisement
Add Comment
Please, Sign In to add comment