colour-dec-api / app.py
Snehal19's picture
Update app.py
5c582cd verified
import gradio as gr
import stone
import tempfile
import os
def get_primary_color(image):
"""
Detects the single most dominant skin color in the first face detected
by selecting the cluster with the highest percentage.
"""
# Save uploaded image to a temp file
tmp = tempfile.NamedTemporaryFile(suffix=".png", delete=False)
image.save(tmp.name, format="PNG")
tmp_path = tmp.name
tmp.close()
try:
# Run stone to get dominant_colors
result = stone.process(tmp_path, image_type="auto", return_report_image=False)
except Exception as e:
os.remove(tmp_path)
return f"<p style='color:red;'>Error: {e}</p>"
finally:
if os.path.exists(tmp_path):
os.remove(tmp_path)
faces = result.get("faces", [])
if not faces:
return "<p>No face detected.</p>"
# Get the list of (color, percent) for the first face
doms = faces[0].get("dominant_colors", [])
if not doms:
return "<p>No skin colors found.</p>"
# Pick the one with max percent
best = max(doms, key=lambda c: c.get("percent", 0))
hexcode = best.get("color")
if not hexcode:
return "<p>No valid color found.</p>"
# Render a single swatch + hex code
swatch_html = (
f"<div style='display:flex; align-items:center; gap:8px;'>"
f"<div style='background:{hexcode}; width:50px; height:50px; "
"border-radius:4px; border:1px solid #ccc;'></div>"
f"<span style='font-family:monospace; font-size:1.2em;'>{hexcode}</span>"
"</div>"
)
return swatch_html
with gr.Blocks() as demo:
gr.Markdown("## 🎯 Primary Face Skin Color")
gr.Markdown("Upload a portrait and get the **most dominant** skin‑tone color.")
with gr.Row():
inp = gr.Image(type="pil", label="Your Photo")
btn = gr.Button("Detect Color")
out = gr.HTML(label="Primary Skin Color")
btn.click(fn=get_primary_color, inputs=inp, outputs=out)
if __name__ == "__main__":
demo.launch()