noddysnots commited on
Commit
828a3cb
Β·
verified Β·
1 Parent(s): 233f919

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +117 -44
app.py CHANGED
@@ -1,52 +1,125 @@
1
  import gradio as gr
2
  from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
3
  import torch
 
 
4
 
5
- # βœ… Use Llama 2 - 7B Chat (Public)
6
- model_name = "meta-llama/Llama-2-7b-chat-hf"
7
-
8
- # πŸ”Ή Authenticate if required (for gated models)
9
- tokenizer = AutoTokenizer.from_pretrained(model_name, use_auth_token=True)
10
- model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, device_map="auto")
11
-
12
- pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, max_new_tokens=100)
13
-
14
- # 🎯 Extract interests from user input
15
- def extract_interests(text):
16
- prompt = f"Extract 3-5 keywords from this: '{text}' (focus on hobbies & products)."
17
- response = pipe(prompt)
18
- interests = response[0]["generated_text"].replace(prompt, "").strip()
19
- return interests.split(", ")
20
-
21
- # 🎁 Web search for gift suggestions
22
- def search_gifts(interests):
23
- query = "+".join(interests)
24
- return {
25
- "Amazon": f"https://www.amazon.in/s?k={query}",
26
- "Flipkart": f"https://www.flipkart.com/search?q={query}",
27
- "IGP": f"https://www.igp.com/search?q={query}",
28
- "IndiaMart": f"https://dir.indiamart.com/search.mp?ss={query}",
29
- }
30
-
31
- # 🎯 Main function for gift recommendation
32
- def recommend_gifts(text):
33
- if not text:
34
- return "Please enter a description."
35
 
36
- interests = extract_interests(text)
37
- links = search_gifts(interests)
38
-
39
- return {"Predicted Interests": interests, "Gift Suggestions": links}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
- # 🎨 Gradio UI
42
- demo = gr.Interface(
43
- fn=recommend_gifts,
44
- inputs="text",
45
- outputs="json",
46
- title="🎁 AI Gift Recommender (Llama 2 - 7B)",
47
- description="Enter details about the person and get personalized gift suggestions with shopping links!",
48
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
- # πŸš€ Launch Gradio App
51
  if __name__ == "__main__":
52
- demo.launch()
 
 
1
  import gradio as gr
2
  from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
3
  import torch
4
+ import requests
5
+ from typing import List, Dict
6
 
7
+ class GiftRecommender:
8
+ def __init__(self, model_name: str = "deepseek-ai/deepseek-coder-6.7b-base"):
9
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
10
+ print(f"Using device: {self.device}")
11
+
12
+ # Initialize tokenizer
13
+ self.tokenizer = AutoTokenizer.from_pretrained(
14
+ model_name,
15
+ trust_remote_code=True
16
+ )
17
+
18
+ # Initialize model with appropriate settings
19
+ self.model = AutoModelForCausalLM.from_pretrained(
20
+ model_name,
21
+ torch_dtype=torch.float16 if self.device == "cuda" else torch.float32,
22
+ device_map="auto",
23
+ trust_remote_code=True,
24
+ low_cpu_mem_usage=True
25
+ )
26
+
27
+ # Create pipeline
28
+ self.generator = pipeline(
29
+ "text-generation",
30
+ model=self.model,
31
+ tokenizer=self.tokenizer,
32
+ device_map="auto"
33
+ )
 
 
 
34
 
35
+ def extract_interests(self, text: str) -> List[str]:
36
+ """Extract interests from user input."""
37
+ try:
38
+ prompt = (
39
+ f"Extract 3-5 relevant interests or keywords from this text as a comma-separated list. "
40
+ f"Focus on hobbies and product preferences: '{text}'"
41
+ )
42
+
43
+ # Generate response with controlled parameters
44
+ response = self.generator(
45
+ prompt,
46
+ max_length=100,
47
+ num_return_sequences=1,
48
+ temperature=0.7,
49
+ top_p=0.95,
50
+ do_sample=True
51
+ )
52
+
53
+ # Clean and process the response
54
+ generated_text = response[0]["generated_text"].replace(prompt, "").strip()
55
+ interests = [item.strip() for item in generated_text.split(",") if item.strip()]
56
+
57
+ return interests[:5] # Ensure we return max 5 interests
58
+
59
+ except Exception as e:
60
+ print(f"Error in interest extraction: {str(e)}")
61
+ return ["general gifts"] # Fallback interests
62
+
63
+ def generate_search_links(self, interests: List[str]) -> Dict[str, str]:
64
+ """Generate shopping links based on interests."""
65
+ query = "+".join(interests)
66
+
67
+ return {
68
+ "Amazon India": f"https://www.amazon.in/s?k={query}",
69
+ "Flipkart": f"https://www.flipkart.com/search?q={query}",
70
+ "IGP Gifts": f"https://www.igp.com/search?q={query}",
71
+ "IndiaMart": f"https://dir.indiamart.com/search.mp?ss={query}"
72
+ }
73
+
74
+ def recommend(self, text: str) -> Dict:
75
+ """Main recommendation function."""
76
+ if not text or not text.strip():
77
+ return {
78
+ "error": "Please enter a description of the person you're buying a gift for."
79
+ }
80
+
81
+ try:
82
+ # Extract interests
83
+ interests = self.extract_interests(text)
84
+
85
+ # Generate shopping links
86
+ links = self.generate_search_links(interests)
87
+
88
+ return {
89
+ "Identified Interests": interests,
90
+ "Shopping Links": links
91
+ }
92
+
93
+ except Exception as e:
94
+ return {
95
+ "error": f"An error occurred: {str(e)}"
96
+ }
97
 
98
+ # Initialize Gradio interface
99
+ def create_gradio_interface():
100
+ # Initialize the recommender
101
+ recommender = GiftRecommender()
102
+
103
+ # Create the interface
104
+ demo = gr.Interface(
105
+ fn=recommender.recommend,
106
+ inputs=gr.Textbox(
107
+ lines=3,
108
+ placeholder="Describe the person you're buying a gift for (their interests, hobbies, age, occasion, etc.)"
109
+ ),
110
+ outputs=gr.JSON(),
111
+ title="🎁 AI Gift Recommender",
112
+ description=(
113
+ "Enter details about the person you're buying a gift for, and get personalized "
114
+ "suggestions with shopping links! The AI will analyze their interests and provide relevant recommendations."
115
+ ),
116
+ examples=[
117
+ ["My friend is a 25-year-old software developer who loves gaming and anime"],
118
+ ["Looking for a gift for my mom who enjoys gardening and cooking"],
119
+ ]
120
+ )
121
+ return demo
122
 
 
123
  if __name__ == "__main__":
124
+ demo = create_gradio_interface()
125
+ demo.launch(share=True) # Enable sharing for testing