AliZain1 commited on
Commit
04f4a36
·
verified ·
1 Parent(s): 710bbce

Upload 4 files

Browse files
Files changed (5) hide show
  1. .gitattributes +1 -0
  2. IMDB_Dataset.csv +3 -0
  3. Notebook.ipynb +0 -0
  4. app.py +162 -0
  5. requirements.txt +8 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ IMDB_Dataset.csv filter=lfs diff=lfs merge=lfs -text
IMDB_Dataset.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:707c8898a0883870cb896a1ed90f6468de200b84b3670534f0d796ef366ebdb0
3
+ size 12489628
Notebook.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
app.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import traceback
3
+ from groq import Groq
4
+ from langchain_groq import ChatGroq
5
+ from langchain.chains import RetrievalQA
6
+ from langchain.prompts import PromptTemplate
7
+ from langchain_huggingface import HuggingFaceEmbeddings
8
+ from langchain_community.vectorstores import Pinecone as PineconeVectorStore
9
+ from pinecone import Pinecone
10
+
11
+ def initialize_recommendation_system():
12
+ try:
13
+ # Initialize Groq
14
+ groq_client = Groq(api_key=st.secrets["GROQ_API_KEY"])
15
+
16
+ # Initialize embeddings
17
+ embeddings = HuggingFaceEmbeddings(
18
+ model_name="sentence-transformers/all-MiniLM-L6-v2"
19
+ )
20
+
21
+ # Initialize Pinecone
22
+ pc = Pinecone(api_key=st.secrets["PINECONE_API_KEY"])
23
+
24
+ # Get the index
25
+ index_name = "imdb-index"
26
+ index = pc.Index(index_name)
27
+
28
+ # Check index stats
29
+ index_stats = index.describe_index_stats()
30
+
31
+ # Initialize vector store
32
+ docsearch = PineconeVectorStore.from_existing_index(
33
+ index_name=index_name,
34
+ embedding=embeddings,
35
+ namespace=""
36
+ )
37
+
38
+ # Initialize LLM
39
+ llm = ChatGroq(
40
+ model_name="llama3-8b-8192",
41
+ api_key=st.secrets["GROQ_API_KEY"],
42
+ temperature=0
43
+ )
44
+
45
+ # Define prompt template
46
+ template = """You are a movie recommender system that helps users find movies that match their preferences.
47
+ Use the following pieces of context to answer the question at the end.
48
+ For each question, suggest three movies, with a short description of the plot and the reason why the user might like it.
49
+ Format your response in a clear, easy-to-read way with line breaks between movies.
50
+ If you don't know the answer, just say that you don't know, don't try to make up an answer.
51
+
52
+ {context}
53
+
54
+ Question: {question}
55
+ Your response:"""
56
+
57
+ PROMPT = PromptTemplate(
58
+ template=template, input_variables=["context", "question"]
59
+ )
60
+
61
+ # Create QA chain
62
+ qa_chain = RetrievalQA.from_chain_type(
63
+ llm=llm,
64
+ chain_type="stuff",
65
+ retriever=docsearch.as_retriever(search_kwargs={"k": 3}),
66
+ return_source_documents=True,
67
+ chain_type_kwargs={"prompt": PROMPT}
68
+ )
69
+
70
+ return qa_chain
71
+
72
+ except Exception as e:
73
+ st.error(f"Error initializing the recommendation system: {str(e)}")
74
+ st.error(traceback.format_exc())
75
+ return None
76
+
77
+ def get_recommendations(query, qa_chain):
78
+ try:
79
+ with st.spinner('🎬 Finding perfect movies for you...'):
80
+ st.write(f"Searching for query: {query}")
81
+ result = qa_chain.invoke({"query": query})
82
+ recommendations = result['result']
83
+ return recommendations
84
+ except Exception as e:
85
+ st.error(f"Error getting recommendations: {str(e)}")
86
+ st.error(traceback.format_exc())
87
+ return None
88
+
89
+ def main():
90
+ # Custom CSS to reduce margins
91
+ st.markdown("""
92
+ <style>
93
+ .block-container {
94
+ padding-left: 2rem !important;
95
+ padding-right: 2rem !important;
96
+ max-width: 95rem !important;
97
+ }
98
+ .stButton button {
99
+ width: 100%;
100
+ }
101
+ </style>
102
+ """, unsafe_allow_html=True)
103
+
104
+ # Initialize session state keys if they don't exist
105
+ if 'initialized' not in st.session_state:
106
+ st.session_state.initialized = False
107
+
108
+ # Header
109
+ st.title("🎬 Movie Recommendation System")
110
+ st.markdown("### Find your next favorite movie!")
111
+
112
+ # Initialize the system if not already done
113
+ if not st.session_state.initialized:
114
+ with st.spinner('Initializing recommendation system...'):
115
+ qa_chain = initialize_recommendation_system()
116
+ if qa_chain:
117
+ st.session_state.qa_chain = qa_chain
118
+ st.session_state.initialized = True
119
+
120
+ # Create columns for layout with adjusted ratios
121
+ col1, col2 = st.columns([3, 1]) # Changed ratio from [2, 1] to [3, 1] for better space utilization
122
+
123
+ with col1:
124
+ # Search input
125
+ query = st.text_input(
126
+ "What kind of movie are you looking for?",
127
+ placeholder="e.g., 'A sci-fi movie with time travel' or 'A romantic comedy set in New York'",
128
+ key="movie_query"
129
+ )
130
+
131
+ # Search button
132
+ if st.button("Get Recommendations 🔍", type="primary"):
133
+ if query:
134
+ recommendations = get_recommendations(query, st.session_state.qa_chain)
135
+ if recommendations:
136
+ # Process and extract movie details
137
+ recommendations_list = recommendations.strip().split('\n')
138
+ formatted_recommendations = []
139
+ for line in recommendations_list:
140
+ # Ensure movie names are detected and formatted
141
+ if "Movie:" in line or line.startswith("*"):
142
+ formatted_recommendations.append(f"**{line.strip()}**")
143
+ else:
144
+ formatted_recommendations.append(line.strip())
145
+
146
+ # Combine into a single formatted block
147
+ final_output = "\n\n".join(formatted_recommendations)
148
+
149
+ # Display recommendations in one box
150
+ st.markdown(f"""
151
+ <div style="border: 1px solid #ddd; border-radius: 8px; padding: 15px; margin-bottom: 15px; box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);">
152
+ <h4>🎥 Movie Recommendations:</h4>
153
+ <p style="white-space: pre-line;">{final_output}</p>
154
+ </div>
155
+ """, unsafe_allow_html=True)
156
+ else:
157
+ st.warning("No recommendations found. Please try a different query.")
158
+ else:
159
+ st.warning("Please enter what kind of movie you're looking for!")
160
+
161
+ if __name__ == "__main__":
162
+ main()
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ streamlit==1.32.2
2
+ groq==0.4.3
3
+ langchain-groq==0.0.5
4
+ langchain==0.1.12
5
+ langchain-huggingface==0.0.9
6
+ langchain-community==0.0.28
7
+ pinecone-client==3.1.0
8
+ sentence-transformers==2.5.1