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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -111
app.py CHANGED
@@ -1,125 +1,75 @@
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
 
1
  import gradio as gr
2
+ from transformers import pipeline
 
3
  import requests
 
4
 
5
+ def extract_interests(text):
6
+ """Extract interests using a smaller, more efficient model"""
7
+ try:
8
+ # Using GPT-2 small model which is more lightweight
9
+ classifier = pipeline(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  "text-generation",
11
+ model="gpt2",
12
+ max_length=50,
13
  device_map="auto"
14
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ prompt = f"List 3 interests from: {text}\nInterests:"
17
+ response = classifier(prompt, max_new_tokens=30, num_return_sequences=1)
18
+
19
+ # Clean up the response
20
+ interests = response[0]['generated_text'].split('Interests:')[-1].strip()
21
+ return [i.strip() for i in interests.split(',') if i.strip()][:3]
22
+ except Exception as e:
23
+ print(f"Error in extraction: {str(e)}")
24
+ return ["general gifts"]
25
+
26
+ def search_gifts(interests):
27
+ """Generate shopping links based on interests"""
28
+ query = "+".join(interests)
29
+ return {
30
+ "Amazon India": f"https://www.amazon.in/s?k={query}",
31
+ "Flipkart": f"https://www.flipkart.com/search?q={query}",
32
+ "IGP Gifts": f"https://www.igp.com/search?q={query}"
33
+ }
34
+
35
+ def recommend_gifts(text):
36
+ """Main recommendation function"""
37
+ if not text:
38
  return {
39
+ "error": "Please enter a description."
 
 
 
40
  }
41
 
42
+ try:
43
+ # Extract interests
44
+ interests = extract_interests(text)
 
 
 
45
 
46
+ # Get shopping links
47
+ links = search_gifts(interests)
48
+
49
+ return {
50
+ "Identified Interests": interests,
51
+ "Shopping Links": links
52
+ }
53
+ except Exception as e:
54
+ return {
55
+ "error": f"An error occurred: {str(e)}"
56
+ }
 
 
 
 
 
57
 
58
+ # Create Gradio interface
59
+ demo = gr.Interface(
60
+ fn=recommend_gifts,
61
+ inputs=gr.Textbox(
62
+ lines=3,
63
+ placeholder="Describe the person you're buying a gift for (their interests, hobbies, age, occasion, etc.)"
64
+ ),
65
+ outputs=gr.JSON(),
66
+ title="🎁 AI Gift Recommender",
67
+ description="Enter details about the person you're buying a gift for, and get personalized suggestions with shopping links!",
68
+ examples=[
69
+ ["My friend is a 25-year-old software developer who loves gaming and anime"],
70
+ ["Looking for a gift for my mom who enjoys gardening and cooking"],
71
+ ]
72
+ )
 
 
 
 
 
 
 
 
 
73
 
74
  if __name__ == "__main__":
75
+ demo.launch()