%matplotlib inline 
from selenium import webdriver
import os,time,json
import pandas as pd
from collections import defaultdict,Counter
import matplotlib.pyplot as plt

url = "http://www.imdb.com/list/ls061683439/"
with open('./filmfare.json',encoding="utf-8") as f:
    datatbl = json.load(f)
driver = webdriver.Chrome(datatbl['data']['chromedriver'])
driver.get(url)

"""
Explanation: Web Scraping & Data Analysis with Selenium and Python
Author: Vinay Babu
Github: https://github.com/min2bro/WebScrapingwithSelenium
Twitter: @min2bro
<img src="./img/DataScienceToolbox.png">
IPython Notebook

Write, Edit, Replay python scripts
Interactive Data Visualization and report Presentation
Notebook can be saved and shared
Run Selenium Python Scripts

Pandas
Matplotlib
<img src="./img/Steps2follow.png">
Analysis of the Filmfare Awards for Best Picture from 1955-2015
<img src="./img/wordcloud2.jpg">
<img src="./img/wordcloud3.png">
Web Scraping: Extracting Data from the Web
End of explanation
"""


def ExtractText(Xpath):
    textlist=[]
    if(Xpath=="Movies_Runtime_Xpath"):
        [textlist.append(item.text[-10:-7]) for item in driver.find_elements_by_xpath(datatbl['data'][Xpath])]
    else:    
        [textlist.append(item.text) for item in driver.find_elements_by_xpath(datatbl['data'][Xpath])]
    return textlist

#Extracting Data from Web
Movies_Votes,Movies_Name,Movies_Ratings,Movies_RunTime=[[] for i in range(4)]
datarepo = [[]]*4
Xpath_list = ['Movies_Name_Xpath','Movies_Rate_Xpath','Movies_Runtime_Xpath','Movies_Votes_Xpath']

for i in range(4):
    if(i==3):
        driver.find_element_by_xpath(datatbl['data']['listview']).click()
    datarepo[i] = ExtractText(Xpath_list[i])
    
driver.quit()

"""
Explanation: Getting Data
End of explanation
"""


# Result in a Python Dictionary
Years=range(2015,1954,-1)
result = defaultdict(dict)
for i in range(0,len(datarepo[0])):
    result[i]['Movie Name']= datarepo[0][i]
    result[i]['Year']= Years[i]
    result[i]['Rating']= datarepo[1][i]
    result[i]['Votes']= datarepo[3][i]
    result[i]['RunTime']= datarepo[2][i]

"""
Explanation: Store Data in a  Python Dictionary
End of explanation
"""


# Dictionary Result
print(json.dumps(result[59], indent=2))

"""
Explanation: Data before Clean Up
End of explanation
"""


for key,values in result.items():
    values['Votes'] = int(values['Votes'].replace(",",""))
    values['Rating']= float(values['Rating'])
    try:
        values['RunTime'] = int(values['RunTime'])
    except ValueError:
        values['RunTime'] = 0
        
    

print(json.dumps(result[0], indent=2))

"""
Explanation: Clean Data
End of explanation
"""


# Dictionary Result
print(json.dumps(result[0], indent=2))

"""
Explanation: How does data in Dictionary looks like
End of explanation
"""


# create dataframe
df = pd.DataFrame.from_dict(result,orient='index')
df.sort_values(by='Year',ascending=True,inplace=True)
df = df[['Year', 'Movie Name', 'Rating', 'Votes','RunTime']]
df

"""
Explanation: Data in Pandas Dataframe
End of explanation
"""


#Highest Rating Movies
df.sort_values('Rating',ascending=[False]).head(5)

"""
Explanation: Movies with Highest Ratings
End of explanation
"""


#Movies with maximum Run Time
df.sort_values(['RunTime'],ascending=[False]).head(10)

"""
Explanation: Movies with Maximum Run time
End of explanation
"""


df.plot(x=df.Year,y=['RunTime']);

"""
Explanation: Best Picture Run time
End of explanation
"""


#Rating Greater than 7
df[(df['Rating']>=7)]['Rating'].count()

#Create Rating Graph
Rating_Hist = defaultdict(dict)

Rating_Hist['Btwn 6&7'] = df[(df['Rating']>=6)&(df['Rating']<7)]['Rating'].count()
Rating_Hist['GTEQ 8'] = df[(df['Rating']>=8)]['Rating'].count()
Rating_Hist['Btwn 7 & 8'] = df[(df['Rating']>=7)&(df['Rating']<8)]['Rating'].count()

plt.bar(range(len(Rating_Hist)), Rating_Hist.values(), align='center',color='brown',width=0.4)
plt.xticks(range(len(Rating_Hist)), Rating_Hist.keys(), rotation=25);

#Histogram for average movie run timr
df['RunTime'].mean()


"""
Explanation: Best Picture Ratings
End of explanation
"""


# Movies by Genre
Category=Counter(datatbl['data']['Genre'])
df1 = pd.DataFrame.from_dict(Category,orient='index')
df1 = df1.sort_values([0],ascending=[False]).head(5)
df1.plot(kind='barh',color=['g','c','m']);

# Vote vs rating
%matplotlib inline 
import matplotlib.pyplot as plt
df.plot(x=df.Votes,y=['Rating'],kind='scatter');
# plt.scatter(df.Votes, df.Rating, s=df.Rating)

import numpy as np
df = pd.DataFrame(np.random.randint(100000, size=(10000, 2)), 
                  columns=['Votes', 'Rating'])

df.plot(kind='scatter', x='Votes', y='Rating', logx=True, alpha=0.5, color='purple', edgecolor='')
plt.ylabel('IMDB Rating')
plt.xlabel('Number of Votes')
plt.show()

"""
Explanation: Best Picture by Genre
End of explanation
"""


