File size: 3,653 Bytes
48e7cc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import gradio as gr
import torch
from flair.data import Sentence
from flair.models import SequenceTagger
import requests
import re
from bs4 import BeautifulSoup

# Load FashionNLP (Flair-based NER model)
tagger = SequenceTagger.load("flair/ner-english-large")

# Regex for extracting price
price_pattern = re.compile(r'(\bunder\b|\babove\b|\bbelow\b|\bbetween\b)?\s?(\d{1,5})\s?(AED|USD|EUR)?', re.IGNORECASE)

# Keywords for gender extraction
gender_keywords = ["men", "male", "women", "female", "unisex"]

def extract_fashion_entities(text):
    """
    Extracts fashion-related entities (Brand, Category, Material, Price, Gender) from text.
    """
    sentence = Sentence(text)
    tagger.predict(sentence)

    extracted_entities = {"Brand": "Unknown", "Category": "Unknown", "Material": "Unknown", "Price": "Unknown", "Gender": "Unknown"}

    for entity in sentence.get_spans('ner'):
        entity_text = entity.text
        entity_label = entity.tag

        if entity_label in ["ORG", "BRAND", "HOUSE"]:
            extracted_entities["Brand"] = entity_text
        elif entity_label in ["PRODUCT", "CATEGORY"]:
            extracted_entities["Category"] = entity_text
        elif entity_label in ["MATERIAL"]:
            extracted_entities["Material"] = entity_text
        elif entity_label in ["PRICE"]:
            extracted_entities["Price"] = entity_text
        elif entity_label in ["GENDER"]:
            extracted_entities["Gender"] = entity_text

    # Extract gender
    for gender in gender_keywords:
        if gender in text.lower():
            extracted_entities["Gender"] = gender.capitalize()
            break

    # Extract price if not found by NER
    price_match = price_pattern.search(text)
    if price_match and extracted_entities["Price"] == "Unknown":
        condition, amount, currency = price_match.groups()
        extracted_entities["Price"] = f"{condition.capitalize() if condition else ''} {amount} {currency if currency else 'AED'}".strip()

    return extracted_entities

def scrape_fashion_trends(url):
    """
    Scrapes fashion trend articles from a given URL and extracts key entities.
    """
    headers = {'User-Agent': 'Mozilla/5.0'}
    response = requests.get(url, headers=headers)
    
    if response.status_code != 200:
        return {"Error": "Unable to fetch data"}
    
    soup = BeautifulSoup(response.text, 'html.parser')
    
    # Extract article text
    paragraphs = soup.find_all("p")
    text = " ".join([p.text for p in paragraphs])

    # Run entity extraction
    extracted_trends = extract_fashion_entities(text)
    
    return extracted_trends

# Define Gradio UI
def parse_fashion_query(user_query):
    """
    Parses a fashion search query and extracts structured attributes.
    """
    return extract_fashion_entities(user_query)

with gr.Blocks() as demo:
    gr.Markdown("# πŸ›οΈ Luxury Fashion Query Parser using FashionNLP")

    with gr.Tab("Search Query Parser"):
        query_input = gr.Textbox(label="Enter your search query", placeholder="e.g., Gucci men’s perfume under 200AED")
        output_box = gr.JSON(label="Parsed Output")
        parse_button = gr.Button("Parse Query")
        parse_button.click(parse_fashion_query, inputs=[query_input], outputs=[output_box])

    with gr.Tab("Fashion Trends Analyzer"):
        url_input = gr.Textbox(label="Enter Fashion News URL", placeholder="e.g., https://www.vogue.com/fashion")
        trends_output = gr.JSON(label="Extracted Trends")
        scrape_button = gr.Button("Analyze Trends")
        scrape_button.click(scrape_fashion_trends, inputs=[url_input], outputs=[trends_output])

demo.launch()