Spaces:
Running
Running
import gradio as gr | |
from transformers import pipeline | |
import urllib.parse | |
def extract_keywords(text: str, nlp_pipeline) -> list: | |
"""Extract relevant keywords from the input text""" | |
prompt = f"Extract 3-4 most relevant gift-related keywords from: {text}\nKeywords:" | |
response = nlp_pipeline(prompt, max_new_tokens=30, num_return_sequences=1) | |
keywords = response[0]['generated_text'].split('Keywords:')[-1].strip() | |
return [k.strip() for k in keywords.split(',') if k.strip()] | |
def generate_search_urls(keywords: list) -> dict: | |
"""Generate search URLs for various e-commerce platforms""" | |
# Encode queries properly for URLs | |
query = urllib.parse.quote(" ".join(keywords)) | |
return { | |
"Amazon India": f'<a href="https://www.amazon.in/s?k={query}" target="_blank">Amazon</a>', | |
"Flipkart": f'<a href="https://www.flipkart.com/search?q={query}" target="_blank">Flipkart</a>', | |
"IGP Gifts": f'<a href="https://www.igp.com/search?q={query}" target="_blank">IGP</a>', | |
"IndiaMart": f'<a href="https://www.indiamart.com/find?q={query}" target="_blank">IndiaMart</a>', | |
} | |
def recommend_gifts(text: str): | |
"""Main function to generate gift recommendations""" | |
if not text: | |
return "β οΈ Please provide a description." | |
try: | |
# Load GPT-2 as a text-generation model | |
nlp = pipeline( | |
"text-generation", | |
model="gpt2", | |
device_map="auto" | |
) | |
# Extract relevant keywords | |
keywords = extract_keywords(text, nlp) | |
# Generate search URLs | |
search_links = generate_search_urls(keywords) | |
# Format the output as clickable links | |
formatted_output = f""" | |
<h3>π Predicted Interests: {", ".join(keywords)}</h3> | |
<h3>π Gift Suggestions:</h3> | |
<ul> | |
<li>{search_links["Amazon India"]}</li> | |
<li>{search_links["Flipkart"]}</li> | |
<li>{search_links["IGP Gifts"]}</li> | |
<li>{search_links["IndiaMart"]}</li> | |
</ul> | |
""" | |
return formatted_output | |
except Exception as e: | |
return f"β Error: {str(e)}" | |
# Create Gradio interface with HTML output | |
demo = gr.Interface( | |
fn=recommend_gifts, | |
inputs=gr.Textbox( | |
lines=3, | |
placeholder="Describe who you're buying a gift for (age, interests, occasion, etc.)" | |
), | |
outputs=gr.HTML(), # Change output type to HTML | |
title="π Smart Gift Recommender", | |
description="Get personalized gift suggestions with direct shopping links!", | |
examples=[ | |
["a small kid of age 3 want him to have something like a toy that teaches alphabets"], | |
["age is 25 and he loves puzzle and online FPS games"], | |
["Looking for a gift for my mom who enjoys gardening and cooking"] | |
] | |
) | |
if __name__ == "__main__": | |
demo.launch() | |