SizeRecommend / app.py
carsten12's picture
Create app.py
012ab87 verified
Raw History Blame Contribute Delete
6.17 kB
import gradio as gr
import json
import re
# ───── Utility: Robust Size‐Table Parser ─────
def parse_size_table(raw_table: str) -> dict:
"""
Take a messy, copy‐pasted size chart (free‐form, tab- or multi-space-separated)
and convert it into a dict of { size_label: {measurement_name: value, ...}, ... }.
- Splits on tabs OR 2+ spaces to handle most spreadsheet→text copies.
- Stops parsing once it hits 'TOP LENGTHS' or 'Tall sizes', ignoring footer notes.
"""
lines = raw_table.strip().splitlines()
table_lines = []
# 1) Collect only the "data" portion, skip footers like "TOP LENGTHS" etc.
for line in lines:
if re.search(r"TOP LENGTHS", line, re.IGNORECASE) or re.search(r"Tall sizes", line, re.IGNORECASE):
break
if not line.strip():
continue
table_lines.append(line.rstrip())
if len(table_lines) < 2:
return {}
# 2) Determine a splitting regex: tabs OR two-or-more spaces
split_pattern = re.compile(r"\t| {2,}")
# 3) Parse header row
header_cols = split_pattern.split(table_lines[0].strip())
# We expect something like ["Hco","EU","Chest (cm)","Arm Length (cm)", ...]
# Our logic will skip the first two columns ("Hco","EU") and only read measurements
sizes_dict = {}
for row in table_lines[1:]:
parts = split_pattern.split(row.strip())
if len(parts) < 3:
# If there aren’t at least 3 columns, skip
continue
size_label = parts[0].strip()
# We’ll try to parse all columns from index 2 onward
measurement_map = {}
for i, col_name in enumerate(header_cols[2:], start=2):
if i >= len(parts):
# missing column in this row
continue
raw_val = parts[i].strip()
if not raw_val:
continue
# If it’s a range like "88-95" or "103–110", extract numbers and average them
num_matches = re.findall(r"\d+(?:\.\d+)?", raw_val)
if len(num_matches) == 2:
low, high = map(float, num_matches)
measurement_map[col_name.strip()] = (low + high) / 2.0
elif len(num_matches) == 1:
measurement_map[col_name.strip()] = float(num_matches[0])
else:
# Could not parse a number—skip
continue
if measurement_map:
sizes_dict[size_label] = measurement_map
return sizes_dict
# ───── Core: Size‐Recommendation Logic ─────
def recommend_fit(raw_table: str, user_data_str: str) -> dict:
"""
1) Parse raw pasted table into structured JSON (size → {measurements}).
2) Parse user_data_str (JSON) into a dict.
3) For each size: compute average % deviation across all measurements present in both.
4) Return the size with smallest average deviation as 'recommended_size';
also compute a 'fit_score' = max(0, 100 - avg_deviation).
5) Return per-measurement fit detail: "Good" if <5% off, "Okay" if <10%, else "Bad".
"""
# 1) Parse the pasted table
try:
size_chart = parse_size_table(raw_table)
except Exception as e:
return {"error": f"Parsing table failed: {e}"}
# 2) Parse user measurements JSON
try:
user_data = json.loads(user_data_str)
if not isinstance(user_data, dict):
raise ValueError("User measurements must be a JSON object mapping measurement→value.")
except Exception as e:
return {"error": f"Invalid user data JSON: {e}"}
if not size_chart:
return {"error": "No valid rows found in the size chart."}
best_size = None
best_score = float("inf")
best_details = {}
# 3) Compare each size
for size_label, measurements in size_chart.items():
total_pct_diff = 0.0
count = 0
fit_detail = {}
for part_name, ideal_val in measurements.items():
if part_name in user_data:
try:
user_val = float(user_data[part_name])
except:
continue
diff = abs(user_val - ideal_val)
pct_diff = (diff / ideal_val) * 100 if ideal_val != 0 else 100
total_pct_diff += pct_diff
count += 1
if pct_diff < 5:
fit_detail[part_name] = "Good"
elif pct_diff < 10:
fit_detail[part_name] = "Okay"
else:
fit_detail[part_name] = "Bad"
if count == 0:
# No overlapping measurements between this size and user_data
continue
avg_pct_diff = total_pct_diff / count
if avg_pct_diff < best_score:
best_score = avg_pct_diff
best_size = size_label
best_details = fit_detail
if best_size is None:
return {"error": "Could not match any size—check your table format or user measurements."}
fit_score = max(0, 100 - best_score)
return {
"recommended_size": best_size,
"fit_score": round(fit_score, 2),
"size_match_details": best_details
}
# ───── Gradio Interface ─────
iface = gr.Interface(
fn=recommend_fit,
inputs=[
gr.Textbox(
lines=15,
label="Pasted Size Table",
placeholder="Paste your brand’s size chart here (tab- or space-separated)..."
),
gr.Textbox(
lines=5,
label="User Measurements (JSON)",
placeholder='e.g. {"Chest (cm)": 90, "Arm Length (cm)": 83}'
)
],
outputs="json",
title="👕 Clothing Size Recommender",
description=(
"1) Copy-paste a raw size table (tabs or multiple spaces). \n"
"2) Provide user body measurements as JSON. \n"
"3) App will return a recommended size + fit breakdown."
)
)
# When running under Docker (Hugging Face Spaces), bind to 0.0.0.0:7860
if __name__ == "__main__":
iface.launch(server_name="0.0.0.0", server_port=7860)