<jupyter_start><jupyter_text>![alt text](CodeCogsEqn.png)<jupyter_code>gaussian_filter_2d = lambda x,y,sigma: np.exp((-x**2 -y**2)/(2 * sigma ** 2))
def dynamic_dimension(chosen_index): 
    labels = []
    if movies.director_name.iloc[chosen_index]:
        labels += [movies.director_name.iloc[chosen_index]]
    if movies.actor_1_name.iloc[chosen_index]:
        labels += [movies.actor_1_name.iloc[chosen_index]]
    if movies.actor_2_name.iloc[chosen_index]:
        labels += [movies.actor_1_name.iloc[chosen_index]]
    if movies.actor_3_name.iloc[chosen_index]:
        labels += [movies.actor_3_name.iloc[chosen_index]]
    if movies.original_language.iloc[chosen_index]:
        labels += [movies.original_language.iloc[chosen_index]]
    if movies.plot_keywords.iloc[chosen_index]:
        labels += movies.plot_keywords.iloc[chosen_index].split('|')
    return labels
def add_dimension(df, variables, columns):
    shape_len = df.shape[1]
    df = np.hstack([df, np.zeros((df.shape[0], len(variables)))])
    for i in columns:
        for k in range(df.shape[0]):
            if not df[k,i]:
                continue
            try:
                for s in df[k,i].split('|'):
                    if s in variables:
                        df[k,shape_len+variables.index(s)] += 1
            except Exception as e:
                continue
    return df
def recommend(chosen_index, count_neigh):
    df_copy = movies.copy().values
    variables = list_genres + dynamic_dimension(chosen_index)
    df_copy = add_dimension(df_copy, variables, [4,12,13,14,15,16])
    df_copy = df_copy[:,movies.shape[1]:].astype('float')
    df_copy = df_copy[~np.isnan(df_copy).any(axis=1)]
    neighbors = NearestNeighbors(n_neighbors=count_neigh+1, algorithm='auto', metric='sqeuclidean').fit(df_copy)
    xtest = df_copy[chosen_index, :]
    xtest = xtest.reshape(1, -1)
    distances, indices = neighbors.kneighbors(xtest)
    results = indices[0][:].tolist()
    try:
        del results[results.index(chosen_index)]
    except:
        results=results[:count_neigh]
        pass
    return results
ironman_index = np.argmax([fuzz.ratio('Iron Man', i) for i in movies.original_title.values])
suggest_number = 10
print('ironman selected:')
print(movies.iloc[ironman_index,:])
recommended = recommend(ironman_index, suggest_number)
movies.iloc[recommended,:]
def sequel(title_1, title_2):    
    if fuzz.ratio(title_1, title_2) > 70 or fuzz.token_set_ratio(title_1, title_2) > 70:
        return True
    else:
        return False

def sort_distribution(title_main, std_count, std_date, title, vote, count, date, popularity):
    if vote:
        factor_e_left = gaussian_filter_2d(vote, count, std_count)
    else:
        factor_e_left = -999999999
    if sequel(title_main, title):
        gaussian_left = 0
    else:
        gaussian_left = (1 / (np.pi * 2 * std_count ** 2)) * factor_e_left
    
    if popularity:
        factor_e_right = gaussian_filter_2d(popularity, date, std_date)
    else:
        factor_e_right = -999999999
    gaussian_right = (1 / (np.pi * 2 * std_date ** 2)) * factor_e_right
    return (gaussian_left + gaussian_right) / 2
def extract_ratings(chosen_index, list_films, count_neigh):
    parametres_movie = ['_' for _ in range(count_neigh)]
    counts, dates = [],[]
    for i, index in enumerate(list_films):
        parametres_movie[i] = movies[['original_title','vote_average','vote_count','release_date','popularity']].iloc[index].tolist()
        parametres_movie[i].append(index)
        counts.append(parametres_movie[i][2])
        dates.append(parametres_movie[i][3])
    
    title_main = movies['original_title'].iloc[chosen_index]
    counts.append(movies['vote_count'].iloc[chosen_index])
    dates.append(movies['release_date'].iloc[chosen_index])
    std_counts = np.std(counts)
    std_dates = np.std(dates)
    results_gaussian = [sort_distribution(title_main,std_counts,std_dates,x[0],x[1],x[2],x[3],x[4]) for x in parametres_movie]
    results = np.array(parametres_movie)[(np.array(results_gaussian).argsort())]
    return results[:,-1].tolist()
ironman_index = np.argmax([fuzz.ratio('Iron Man', i) for i in movies.original_title.values])
suggest_number = 10
print('ironman selected:')
print(movies.iloc[ironman_index,:])
recommended = recommend(ironman_index, suggest_number)
sorted_recommended = np.array(extract_ratings(ironman_index, recommended, suggest_number)).astype('int')
movies.iloc[sorted_recommended,:]<jupyter_output>ironman selected:
adult                                                            False
budget                                                       140000000
genres                                Action|Science Fiction|Adventure
id                                                                1726
original_language                                                   en
original_title                                                Iron Man
popularity                                                     22.0731
release_date                                                      2008
revenue                                                    5.85174e+08
runtime                                                            126
vote_average                                                       7.4
vote_count                                                        8951
plot_keywords        middle east|arms dealer|malibu|marvel comic|su...
actor_1_name                                         Robert[...]<jupyter_text>remove sequel<jupyter_code>outputs, i = [], 0
while len(outputs) < suggest_number:
    recommended = recommend(ironman_index, suggest_number * (i+2))
    if not sequel(movies['original_title'].iloc[ironman_index], movies['original_title'].iloc[recommended[i]]) and recommended[i] not in outputs:
        outputs.append(recommended[i])
    i += 1
sorted_recommended = np.array(extract_ratings(ironman_index,outputs,suggest_number)).astype('int')
movies.iloc[sorted_recommended,:]
def suggest_me_movies(keyword, suggest_count, remove_sequel=True):
    lasttime = time.time()
    your_index = np.argmax([fuzz.ratio(keyword, i) for i in movies['original_title'].values])
    print('your selection:')
    print(movies.iloc[your_index,:])
    if remove_sequel:
        outputs, i = [], 0
        while len(outputs) < suggest_count:
            recommended = recommend(your_index, suggest_count * (i+2))
            if not sequel(movies['original_title'].iloc[your_index], movies['original_title'].iloc[recommended[i]]) and recommended[i] not in outputs:
                outputs.append(recommended[i])
            i += 1
        results = np.array(extract_ratings(your_index,outputs,suggest_count)).astype('int')
    else:
        recommended = recommend(your_index, suggest_count)
        results = np.array(extract_ratings(your_index,recommended,suggest_count)).astype('int')
    print('time taken to suggest:', time.time()-lasttime, 'seconds')
    return results
movies.iloc[suggest_me_movies('cinderella', 15, remove_sequel=True),:]
movies.iloc[suggest_me_movies('cinderella', 15, remove_sequel=False),:]
movies.iloc[suggest_me_movies('the mummy', 30, remove_sequel=True),:]<jupyter_output>your selection:
adult                                                            False
budget                                                        80000000
genres                                        Adventure|Action|Fantasy
id                                                                 564
original_language                                                   en
original_title                                               The Mummy
popularity                                                     23.9841
release_date                                                      1999
revenue                                                    4.15885e+08
runtime                                                            124
vote_average                                                       6.6
vote_count                                                        2796
plot_keywords        library|secret passage|cairo|egypt|pastor|pyra...
actor_1_name                                            Brend[...]
{'fraction_non_alphanumeric': 0.10613639136269366, 'fraction_numerical': 0.021227278272538733, 'mean_word_length': 2.1088357982555936, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 4, 'word_list_counts': {'cursed_substrings.json': 49, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '231450', 'license': 'MIT', 'n_tokens_mistral': 2512, 'n_tokens_neox': 2332, 'n_words': 414, 'path': 'Suggestion-Engine/3.movie.ipynb', 'repo_name': 'huseinzol05/Machine-Learning-Data-Science-Reuse', 'size': '8197'}