Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import numpy as np
|
| 5 |
+
from torch_geometric.data import Data
|
| 6 |
+
from torch_geometric.nn import GATConv
|
| 7 |
+
from sentence_transformers import SentenceTransformer
|
| 8 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
| 9 |
+
|
| 10 |
+
# Define the GATConv model architecture
|
| 11 |
+
class ModeratelySimplifiedGATConvModel(torch.nn.Module):
|
| 12 |
+
def __init__(self, in_channels, hidden_channels, out_channels):
|
| 13 |
+
super().__init__()
|
| 14 |
+
self.conv1 = GATConv(in_channels, hidden_channels, heads=2)
|
| 15 |
+
self.dropout1 = torch.nn.Dropout(0.45)
|
| 16 |
+
self.conv2 = GATConv(hidden_channels * 2, out_channels, heads=1)
|
| 17 |
+
|
| 18 |
+
def forward(self, x, edge_index, edge_attr=None):
|
| 19 |
+
x = self.conv1(x, edge_index, edge_attr)
|
| 20 |
+
x = torch.relu(x)
|
| 21 |
+
x = self.dropout1(x)
|
| 22 |
+
x = self.conv2(x, edge_index, edge_attr)
|
| 23 |
+
return x
|
| 24 |
+
|
| 25 |
+
# Load the dataset and the GATConv model
|
| 26 |
+
data = torch.load("graph_data.pt", map_location=torch.device("cpu"))
|
| 27 |
+
|
| 28 |
+
# Correct the state dictionary's key names
|
| 29 |
+
original_state_dict = torch.load("graph_model.pth", map_location=torch.device("cpu"))
|
| 30 |
+
corrected_state_dict = {}
|
| 31 |
+
for key, value in original_state_dict.items():
|
| 32 |
+
if "lin.weight" in key:
|
| 33 |
+
corrected_state_dict[key.replace("lin.weight", "lin_src.weight")] = value
|
| 34 |
+
corrected_state_dict[key.replace("lin.weight", "lin_dst.weight")] = value
|
| 35 |
+
else:
|
| 36 |
+
corrected_state_dict[key] = value
|
| 37 |
+
|
| 38 |
+
# Initialize the GATConv model with the corrected state dictionary
|
| 39 |
+
gatconv_model = ModeratelySimplifiedGATConvModel(
|
| 40 |
+
in_channels=data.x.shape[1], hidden_channels=32, out_channels=768
|
| 41 |
+
)
|
| 42 |
+
gatconv_model.load_state_dict(corrected_state_dict)
|
| 43 |
+
|
| 44 |
+
# Load the BERT-based sentence transformer model
|
| 45 |
+
model_bert = SentenceTransformer("all-mpnet-base-v2")
|
| 46 |
+
|
| 47 |
+
# Ensure the DataFrame is loaded properly
|
| 48 |
+
df = pd.read_feather("EmbeddedCombined.feather")
|
| 49 |
+
|
| 50 |
+
# Generate GNN-based embeddings
|
| 51 |
+
with torch.no_grad():
|
| 52 |
+
all_video_embeddings = gatconv_model(data.x, data.edge_index, data.edge_attr).cpu()
|
| 53 |
+
|
| 54 |
+
# Function to find the most similar video and recommend the top 10 based on GNN embeddings
|
| 55 |
+
def get_similar_and_recommend(input_text):
|
| 56 |
+
# Find the most similar video based on input text
|
| 57 |
+
embeddings_matrix = np.array(df["embeddings"].tolist())
|
| 58 |
+
input_embedding = model_bert.encode([input_text])[0]
|
| 59 |
+
similarities = cosine_similarity([input_embedding], embeddings_matrix)[0]
|
| 60 |
+
most_similar_index = np.argmax(similarities)
|
| 61 |
+
|
| 62 |
+
most_similar_video = {
|
| 63 |
+
"title": df["title"].iloc[most_similar_index],
|
| 64 |
+
"description": df["description"].iloc[most_similar_index],
|
| 65 |
+
"similarity_score": similarities[most_similar_index],
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
# Recommend the top 10 videos based on GNN embeddings and dot product
|
| 69 |
+
def recommend_next_10_videos(given_video_index, all_video_embeddings):
|
| 70 |
+
dot_products = [
|
| 71 |
+
torch.dot(all_video_embeddings[given_video_index].cpu(), all_video_embeddings[i].cpu())
|
| 72 |
+
for i in range(all_video_embeddings.shape[0])
|
| 73 |
+
]
|
| 74 |
+
dot_products[given_video_index] = -float("inf")
|
| 75 |
+
|
| 76 |
+
top_10_indices = np.argsort(dot_products)[::-1][:10]
|
| 77 |
+
recommendations = [df["title"].iloc[idx] for idx in top_10_indices]
|
| 78 |
+
return recommendations
|
| 79 |
+
|
| 80 |
+
top_10_recommendations = recommend_next_10_videos(
|
| 81 |
+
most_similar_index, all_video_embeddings
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
return (
|
| 85 |
+
most_similar_video["title"],
|
| 86 |
+
most_similar_video["description"],
|
| 87 |
+
most_similar_video["similarity_score"],
|
| 88 |
+
top_10_recommendations,
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
# Update the Gradio interface to fix the output type
|
| 92 |
+
interface = gr.Interface(
|
| 93 |
+
fn=get_similar_and_recommend,
|
| 94 |
+
inputs=gr.components.Textbox(label="Enter Text to Find Most Similar Video"),
|
| 95 |
+
outputs=[
|
| 96 |
+
gr.components.Textbox(label="Video Title"),
|
| 97 |
+
gr.components.Textbox(label="Video Description"),
|
| 98 |
+
gr.components.Textbox(label="Similarity Score"),
|
| 99 |
+
gr.components.Textbox(label="Top 10 Recommended Videos", lines=10), # Handle a list
|
| 100 |
+
],
|
| 101 |
+
title="Video Recommendation System with GNN-based Recommendations",
|
| 102 |
+
description="Enter text to find the most similar video and get the top 10 recommended videos based on dot product and GNN embeddings.",
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
# Launch the Gradio interface
|
| 106 |
+
interface.launch()
|