#!/usr/bin/env python # -*- coding: iso-8859-1 -*- from sys import argv import csv import string from AdwordsStats import adwordsStats import YouTubeStats from time import sleep from Emailer import sendFile from Imdb import titleCode def sanitizeString(dirty): clean = "" allowed = string.ascii_letters + string.digits + " -.'\"" for i, v in enumerate(dirty): if allowed.find(str(v)) != -1: clean = clean + str(v) else: clean = clean + " " while clean.find(" ") != -1: clean = clean.replace(" ", " ") return clean.strip() def tryTenTimes(function): count = 10 while count > 0: count = count - 1 try: return function() except Exception as ex: print "Error:", ex, "... sleeping 5." sleep(5) return None emailMessage = "Hello %s,\n\nThis is an automated message. Attached are the requested statistics for these movies:\n" % argv[3][0:argv[3].find('@')] adwords = adwordsStats() listFile = open(argv[1]) outFile = open(argv[2], "wb") output = csv.writer(outFile) header = ["Rank", "Movie", "Google LSV (broad)", "Google LSV (exact)", "Google GSV (broad)", "Google GSV (exact)", "YouTube Search Volume (broad)", "YouTube Search Volume (exact)", "YouTube View Count", "IMDB Title Code"] output.writerow(header) print header i = 0 for line in listFile: i = i + 1 movie = line.strip() emailMessage = emailMessage + "\n * %s" % movie searchString = sanitizeString(movie) google = tryTenTimes(lambda: adwords.getKeywordStats(searchString)) if google is None: google = { 'broad': { 'gsv': '???', 'lsv': '???' }, 'exact': { 'gsv': '???', 'lsv': '???' } } youtube = tryTenTimes(lambda: YouTubeStats.searchVolume(searchString)) if youtube is None: youtube = { 'broad': '???', 'exact': '???' } yvc = tryTenTimes(lambda: YouTubeStats.viewCount(searchString)) if yvc is None: yvc = '???' imdbTitleCode = tryTenTimes(lambda: titleCode(searchString)) if imdbTitleCode is None: imdbTitleCode = '???' row = [str(i), movie, str(google['broad']['lsv']), str(google['exact']['lsv']), str(google['broad']['gsv']), str(google['exact']['gsv']), str(youtube['broad']), str(youtube['exact']), str(yvc), imdbTitleCode] output.writerow(row) outFile.flush() print row outFile.close() listFile.close() emailMessage += "\n\nEnjoy,\nJason" print "Sending email...", sendFile(argv[3], argv[2], emailMessage) print "sent!"