File size: 3,503 Bytes
af1d8cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import requests
import os

# API_URL = "https://api-inference.huggingface.co/models/google/vit-base-patch16-224"
# Trying ResNet-50 as it's very standard
API_URL = "https://api-inference.huggingface.co/models/microsoft/resnet-50"

def classify_garment(image_path: str):
    """
    Classifies a garment image using Hugging Face API with Filename Fallback.
    """
    
    # 1. Try Keyword Analysis on Filename (Fast & Robust Fallback)
    filename = os.path.basename(image_path).lower()
    bottom_keywords = ["jean", "denim", "trouser", "pant", "skirt", "short", "legging", "sweatpant", "trunks"]
    shoe_keywords = ["shoe", "sneaker", "boot", "sandal", "heel", "loafer", "clog"]
    top_keywords = ["shirt", "jersey", "tee", "top", "blouse", "sweater", "cardigan", "jacket", "coat", "hoodie", "vest"]
    
    fallback_category = "top"
    fallback_desc = "Uploaded Item"
    
    if any(k in filename for k in bottom_keywords):
        fallback_category = "bottom"
        fallback_desc = filename.split('.')[0].replace('_', ' ').title()
        print(f"DEBUG: Filename '{filename}' matches BOTTOM keywords.")
    elif any(k in filename for k in shoe_keywords):
        fallback_category = "shoes"
        fallback_desc = filename.split('.')[0].replace('_', ' ').title()
        print(f"DEBUG: Filename '{filename}' matches SHOES keywords.")
    elif any(k in filename for k in top_keywords):
        fallback_category = "top"
        fallback_desc = filename.split('.')[0].replace('_', ' ').title()
        print(f"DEBUG: Filename '{filename}' matches TOP keywords.")
        
    # 2. Try API
    token = os.environ.get("HF_TOKEN")
    if not token and os.path.exists("hf_token.txt"):
        with open("hf_token.txt", "r") as f:
            token = f.read().strip()
            
    if not token:
        print("Warning: No HF Token. Using filename fallback.")
        return fallback_category, fallback_desc, "untagged"

    headers = {"Authorization": f"Bearer {token}"}
    
    try:
        with open(image_path, "rb") as f:
            data = f.read()
            
        print(f"Calling HF API ({API_URL})...")
        response = requests.post(API_URL, headers=headers, data=data, timeout=5)
        
        if response.status_code != 200:
            print(f"HF API Error: {response.status_code}. Using fallback.")
            return fallback_category, fallback_desc, "api-error"
            
        predictions = response.json()
        
        if not predictions or not isinstance(predictions, list):
            return fallback_category, fallback_desc, "api-unknown"
            
        top_prediction = predictions[0]
        label = top_prediction.get('label', '').lower()
        score = top_prediction.get('score', 0)
        
        print(f"AI Classification: '{label}' ({score:.2f})")
        
        # Map to Category
        category = "top"
        description = label.split(',')[0].title()
        
        if any(k in label for k in bottom_keywords):
            category = "bottom"
        elif any(k in label for k in shoe_keywords):
            category = "shoes"
            
        # SEO Naming
        if "jersey" in label or "tee" in label:
            description = "T-Shirt"
        elif "jean" in label:
            description = "Denim Jeans"
            
        return category, description, label
        
    except Exception as e:
        print(f"Classification Failed: {e}. Using fallback.")
        return fallback_category, fallback_desc, "error"