Spaces:
Sleeping
Sleeping
Upload app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071from fastai.vision.all import *
import gradio as gr
from colorthief import ColorThief
from PIL import Image
import matplotlib.colors as mcolors
import io
import colorsys
# Load the model
learn = load_learner('outfit_recommender_resnet18.pkl')
# Define class names
class_names = ['jeans', 'top']
# Helper function to get the name of the closest color
def closest_color(requested_color):
min_colors = {}
for key, name in mcolors.CSS4_COLORS.items():
r_c, g_c, b_c = mcolors.hex2color(name)
rd = (r_c - requested_color[0]) ** 2
gd = (g_c - requested_color[1]) ** 2
bd = (b_c - requested_color[2]) ** 2
min_colors[(rd + gd + bd)] = key
return min_colors[min(min_colors.keys())]
def get_dominant_color(image):
img_byte_arr = io.BytesIO()
image.save(img_byte_arr, format='PNG')
img_byte_arr = img_byte_arr.getvalue()
color_thief = ColorThief(io.BytesIO(img_byte_arr))
dominant_color = color_thief.get_color(quality=1)
dominant_color = tuple(c / 255 for c in dominant_color) # Normalize RGB values to [0, 1]
return dominant_color
def get_complementary_color(rgb_color):
h, s, v = colorsys.rgb_to_hsv(*rgb_color)
complementary_h = (h + 0.5) % 1.0
r, g, b = colorsys.hsv_to_rgb(complementary_h, s, v)
return closest_color((r, g, b))
def get_outfit_recommendation(pred_class):
if pred_class == 'top':
return 'Jeans'
elif pred_class == 'jeans':
return 'Top'
else:
return 'Item'
def predict(image):
pred_class, pred_idx, outputs = learn.predict(image)
pred_class = class_names[pred_idx] # Convert index to class name
dominant_color = get_dominant_color(image)
complementary_color = get_complementary_color(dominant_color)
garment_recommendation = get_outfit_recommendation(pred_class)
return f"Complementary item: {garment_recommendation} in {complementary_color}"
def gradio_predict(image):
if isinstance(image, np.ndarray):
image = Image.fromarray(image.astype('uint8'), 'RGB')
return predict(image)
interface = gr.Interface(
fn=gradio_predict,
inputs=gr.Image(),
outputs="text",
title="Outfit Recommender",
description="Upload an image of a jeans or a top to get a recommendation for a complementary outfit based on fashion theory."
)
interface.launch()app.pyAdded+71