ash23021 commited on
Commit
fae09c2
·
verified ·
1 Parent(s): 9b19c4e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -90
app.py CHANGED
@@ -1,90 +1,91 @@
1
- # !pip install --upgrade llama-index llama-index-embeddings-huggingface llama-index-llms-huggingface transformers torch accelerate bitsandbytes
2
-
3
- from llama_index.core import Settings, SimpleDirectoryReader, VectorStoreIndex, Document
4
- from llama_index.embeddings.huggingface import HuggingFaceEmbedding
5
- from llama_index.llms.huggingface import HuggingFaceLLM
6
- import torch
7
- import os
8
- import pandas as pd
9
- import gradio as gr
10
-
11
- Settings.embed_model = HuggingFaceEmbedding(model_name="sentence-transformers/all-MiniLM-L6-v2")
12
-
13
-
14
- Settings.embed_model = HuggingFaceEmbedding(
15
- model_name="sentence-transformers/all-MiniLM-L6-v2")
16
- Settings.llm = HuggingFaceLLM(
17
- model_name="TinyLlama/TinyLlama-1.1B-Chat-v1.0",
18
- tokenizer_name="TinyLlama/TinyLlama-1.1B-Chat-v1.0",
19
- context_window=2048,
20
- max_new_tokens=256,
21
- device_map="auto",
22
- model_kwargs={"torch_dtype": torch.float16, "load_in_4bit": True}
23
- )
24
-
25
- csv_file_path = "movie_recommendations_with_names.csv"
26
- df = None
27
-
28
- try:
29
- df = pd.read_csv(csv_file_path)
30
- except FileNotFoundError:
31
- print(f"Error: CSV file not found at {csv_file_path}")
32
- print(f"Current working directory: {os.getcwd()}")
33
-
34
- except Exception as e:
35
- print(f"An unexpected error occurred while reading the CSV: {e}")
36
-
37
- if df is not None:
38
- movies_data = [
39
- Document(text=f"MovieID: {row['movie_id']}, Title: {row['title']}, Genre: {row['genre']}, Rating: {row['rating']}",
40
- metadata={"movie_id": row['movie_id'], "title": row['title'], "genre": row['genre'], "rating": row['rating']})
41
- for index, row in df.iterrows()
42
- ]
43
- index = VectorStoreIndex.from_documents(movies_data)
44
- query_engine = index.as_query_engine()
45
-
46
- def recommend_movie(genre):
47
- if not genre.strip():
48
- return "! Please enter a movie genre."
49
-
50
- response = query_engine.query(
51
- f"List titles and genre of movies with genre {genre}."
52
- f"provide at least 3 recommendations if avalabile."
53
- )
54
-
55
- response_lines= str(response).split("\n")
56
- filtered = [
57
- line for line in response_lines
58
- if line.strip()
59
- and "Note : The query is not specific" not in line
60
- ]
61
-
62
- recommendations = []
63
- for rec in filtered:
64
- if "Title:" in rec:
65
- try:
66
- title = rec.split("Title:")[1].split(",")[0].strip()
67
- recommendations.append(f"{title}")
68
- except:
69
- recommendations.append(f"{rec.strip()}")
70
-
71
- recommendations = recommendations[:5]
72
-
73
- if not recommendations:
74
- return " Sorry , I couldn't find movies for that genre."
75
- return "\n".join(recommendations)
76
- #gradio ui
77
-
78
- interface = gr.Interface(
79
- fn=recommend_movie,
80
- inputs=gr.Textbox(
81
- label="What type of movie are you in the mood for?",
82
- placeholder="e.g. Action, Comedy, Drama, Sci-Fi"
83
- ),
84
- outputs=gr.Textbox(label="🍿 Movie Recommendations"),
85
- title="🎥 MovieRecBot",
86
- description="Movie recommendation system powered by LlamaIndex + TinyLlama (Hugging Face)",
87
- examples=[["Action"], ["Comedy"], ["Romance"], ["Sci-Fi"]],
88
- )
89
- interface.launch(share=True)
90
-
 
 
1
+ # !pip install --upgrade llama-index llama-index-embeddings-huggingface llama-index-llms-huggingface transformers torch accelerate bitsandbytes
2
+
3
+ from llama_index.core import Settings, SimpleDirectoryReader, VectorStoreIndex, Document
4
+ from llama_index.embeddings.huggingface import HuggingFaceEmbedding
5
+ from llama_index.llms.huggingface import HuggingFaceLLM
6
+ import torch
7
+ import os
8
+ import pandas as pd
9
+ import gradio as gr
10
+
11
+ Settings.embed_model = HuggingFaceEmbedding(model_name="sentence-transformers/all-MiniLM-L6-v2")
12
+
13
+
14
+ Settings.embed_model = HuggingFaceEmbedding(
15
+ model_name="sentence-transformers/all-MiniLM-L6-v2")
16
+ Settings.llm = HuggingFaceLLM(
17
+ model_name="TinyLlama/TinyLlama-1.1B-Chat-v1.0",
18
+ tokenizer_name="TinyLlama/TinyLlama-1.1B-Chat-v1.0",
19
+ context_window=2048,
20
+ max_new_tokens=256,
21
+ device_map="auto",
22
+ model_kwargs={"torch_dtype": torch.float16}
23
+ )
24
+
25
+
26
+ csv_file_path = "movie_recommendations_with_names.csv"
27
+ df = None
28
+
29
+ try:
30
+ df = pd.read_csv(csv_file_path)
31
+ except FileNotFoundError:
32
+ print(f"Error: CSV file not found at {csv_file_path}")
33
+ print(f"Current working directory: {os.getcwd()}")
34
+
35
+ except Exception as e:
36
+ print(f"An unexpected error occurred while reading the CSV: {e}")
37
+
38
+ if df is not None:
39
+ movies_data = [
40
+ Document(text=f"MovieID: {row['movie_id']}, Title: {row['title']}, Genre: {row['genre']}, Rating: {row['rating']}",
41
+ metadata={"movie_id": row['movie_id'], "title": row['title'], "genre": row['genre'], "rating": row['rating']})
42
+ for index, row in df.iterrows()
43
+ ]
44
+ index = VectorStoreIndex.from_documents(movies_data)
45
+ query_engine = index.as_query_engine()
46
+
47
+ def recommend_movie(genre):
48
+ if not genre.strip():
49
+ return "! Please enter a movie genre."
50
+
51
+ response = query_engine.query(
52
+ f"List titles and genre of movies with genre {genre}."
53
+ f"provide at least 3 recommendations if avalabile."
54
+ )
55
+
56
+ response_lines= str(response).split("\n")
57
+ filtered = [
58
+ line for line in response_lines
59
+ if line.strip()
60
+ and "Note : The query is not specific" not in line
61
+ ]
62
+
63
+ recommendations = []
64
+ for rec in filtered:
65
+ if "Title:" in rec:
66
+ try:
67
+ title = rec.split("Title:")[1].split(",")[0].strip()
68
+ recommendations.append(f"{title}")
69
+ except:
70
+ recommendations.append(f"{rec.strip()}")
71
+
72
+ recommendations = recommendations[:5]
73
+
74
+ if not recommendations:
75
+ return " Sorry , I couldn't find movies for that genre."
76
+ return "\n".join(recommendations)
77
+ #gradio ui
78
+
79
+ interface = gr.Interface(
80
+ fn=recommend_movie,
81
+ inputs=gr.Textbox(
82
+ label="What type of movie are you in the mood for?",
83
+ placeholder="e.g. Action, Comedy, Drama, Sci-Fi"
84
+ ),
85
+ outputs=gr.Textbox(label="🍿 Movie Recommendations"),
86
+ title="🎥 MovieRecBot",
87
+ description="Movie recommendation system powered by LlamaIndex + TinyLlama (Hugging Face)",
88
+ examples=[["Action"], ["Comedy"], ["Romance"], ["Sci-Fi"]],
89
+ )
90
+ interface.launch(share=True)
91
+