import base64
import html
import io
import logging
import os
import tempfile
from pathlib import Path
import gradio as gr
import numpy as np
import pandas as pd
from PIL import Image, ImageOps
from matcher import ExpressionMatcher
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(message)s")
log = logging.getLogger("app")
REPO = os.environ.get("MODEL_REPO", "23f1000805/face-expression-v3")
HERE = Path(__file__).parent
EX = HERE / "examples"
MODEL = ExpressionMatcher(REPO)
N = len(MODEL.labels)
COLORS = {
"neutral": "#64748b", "happy": "#f59e0b", "sad": "#3b82f6", "angry": "#ef4444", "surprised": "#a855f7",
"contempt": "#14b8a6", "restrained-amusement": "#ec4899", "scepticism": "#84cc16", "uncertainty": "#f97316",
"hopelessness": "#6366f1",
}
def pretty(s):
return s.replace("-", " ").title()
def thumb_uri(path, px=240):
im = ImageOps.exif_transpose(Image.open(path)).convert("RGB")
im = ImageOps.fit(im, (px, px), method=Image.BILINEAR, centering=(0.5, 0.4))
buf = io.BytesIO()
im.save(buf, "JPEG", quality=80)
return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode()
def card(title, label, conf, uri=None, truth=None):
col = COLORS.get(label, "#64748b")
img = f'
' if uri else f'
{html.escape(title)}
'
cap = f'{html.escape(title)}
' if uri else ""
tr = ""
if truth is not None:
ok = truth == label
tr = f'{"match" if ok else "expected " + html.escape(pretty(truth))}
'
return (f'{img}{cap}
{html.escape(pretty(label))}
'
f'
'
f'
{conf * 100:.0f}% confidence
{tr}
')
def heatmap(s, rows):
z = s - s.mean(axis=1, keepdims=True)
z = z / (np.abs(z).max() + 1e-9)
head = "".join(f"{html.escape(pretty(l))} | " for l in MODEL.labels)
body = ""
for i in range(len(s)):
tds = ""
for j in range(N):
a = abs(z[i, j])
c = "34,197,94" if z[i, j] > 0 else "239,68,68"
tds += f'{s[i, j]:.2f} | '
body += f"| {html.escape(rows[i])} | {tds}
"
return f''
def summarise(pred, truth):
if truth is None:
return ""
acc = float(np.mean([MODEL.labels[a] == b for a, b in zip(pred, truth)]))
return f'{acc * 100:.0f}% of this person\'s photos match the expression they were labelled with
'
def block(title, df_rows, pred, p, s, thumbs, truth):
labels = [MODEL.labels[k] for k in pred]
cards = "".join(
card(df_rows[i], labels[i], float(p[i, pred[i]]), thumbs[i] if thumbs else None, truth[i] if truth else None)
for i in range(len(labels))
)
return (f'{html.escape(title)}
{summarise(pred, truth)}{cards}
'
f'Score of every photo for every expression
{heatmap(s, df_rows)} ')
def notice(msg, kind="warn"):
return f'{html.escape(msg)}
'
def to_csv(tbl):
f = tempfile.NamedTemporaryFile("w", suffix=".csv", delete=False, prefix="predictions_")
tbl.to_csv(f, index=False)
f.close()
return f.name
# ---------- photo tab ----------
def run_photos(files, progress=gr.Progress()):
paths = [f[0] if isinstance(f, (tuple, list)) else f for f in (files or [])]
paths = [getattr(p, "name", p) for p in paths]
if len(paths) != N:
return notice(f"Add exactly {N} photos of the same person (you added {len(paths)}). One photo per expression."), None, None
from extractor import extract
progress(0.1, desc="Finding faces and reading expressions")
feats, bad = extract(paths, MODEL.cols)
if bad:
why = "; ".join(f"photo {i + 1}: {m}" for i, m in bad)
return notice(f"Could not use every photo ({why}). Use clear, front facing photos with one visible face."), None, None
progress(0.8, desc="Matching expressions to photos")
pred, s, p = MODEL.match(feats.drop(columns="_idx"))
names = [f"Photo {i + 1}" for i in range(N)]
uris = [thumb_uri(x) for x in paths]
out = block("Result", names, pred, p, s, uris, None)
tbl = pd.DataFrame({"photo": names, "predicted_expression": [MODEL.labels[k] for k in pred],
"confidence": [round(float(p[i, pred[i]]), 3) for i in range(N)]})
return out, tbl, to_csv(tbl)
def list_sets():
if not EX.exists():
return []
return sorted(d.name for d in EX.iterdir() if d.is_dir())
def load_set(name):
if not name:
return gr.update()
d = EX / name
imgs = sorted(p for p in d.iterdir() if p.suffix.lower() in (".jpg", ".jpeg", ".png", ".webp"))
return [str(p) for p in imgs[:N]]
# ---------- csv tab ----------
def run_csv(path):
if not path:
return notice("Upload a features csv or pick an example."), None, None
path = getattr(path, "name", path)
try:
df = pd.read_csv(path)
except Exception as ex:
return notice(f"Could not read that file: {ex}"), None, None
miss = [c for c in MODEL.cols if c not in df.columns]
if miss:
return notice(f"The csv is missing {len(miss)} feature columns, for example {miss[:3]}."), None, None
if "person_id" not in df.columns:
df["person_id"] = "1"
if "photo_id" not in df.columns:
df["photo_id"] = [f"row {i + 1}" for i in range(len(df))]
df["person_id"] = df["person_id"].astype(str)
html_parts, tbls = [], []
people = list(dict.fromkeys(df["person_id"]))
for pid in people:
g = df[df["person_id"] == pid].reset_index(drop=True)
if len(g) != N:
html_parts.append(notice(f"Person {pid} has {len(g)} rows, needs {N}. Skipped."))
continue
pred, s, p = MODEL.match(g)
truth = g["intended_expression"].tolist() if "intended_expression" in g.columns else None
if len(html_parts) < 8:
html_parts.append(block(f"Person {pid}", g["photo_id"].astype(str).tolist(), pred, p, s, None, truth))
t = pd.DataFrame({"person_id": pid, "photo_id": g["photo_id"],
"predicted_expression": [MODEL.labels[k] for k in pred],
"confidence": [round(float(p[i, pred[i]]), 3) for i in range(N)]})
if truth:
t["intended_expression"] = truth
tbls.append(t)
if not tbls:
return "".join(html_parts), None, None
tbl = pd.concat(tbls, ignore_index=True)
head = ""
if "intended_expression" in tbl.columns:
acc = float((tbl["predicted_expression"] == tbl["intended_expression"]).mean())
head = f'{acc * 100:.1f}% matched on {len(tbls)} people (these may be people the model trained on, so this is optimistic)
'
return head + "".join(html_parts), tbl, to_csv(tbl)
def list_csvs():
return sorted(p.name for p in EX.glob("*.csv")) if EX.exists() else []
def pick_csv(name):
return str(EX / name) if name else None
CSS = """
.gradio-container{max-width:1180px!important;margin:auto}
.hero{padding:28px 30px;border-radius:18px;background:linear-gradient(135deg,#4f46e5 0%,#7c3aed 55%,#db2777 100%);color:#fff;margin-bottom:14px}
.hero h1{margin:0 0 6px;font-size:30px;font-weight:700;color:#fff}
.hero p{margin:0;opacity:.92;font-size:15px;line-height:1.5}
.pills{margin-top:14px;display:flex;gap:8px;flex-wrap:wrap}
.pills span{background:rgba(255,255,255,.18);padding:4px 12px;border-radius:999px;font-size:12.5px}
.grid{display:grid;grid-template-columns:repeat(5,1fr);gap:14px;margin:10px 0 14px}
@media(max-width:900px){.grid{grid-template-columns:repeat(2,1fr)}}
.fx-card{background:var(--background-fill-primary);border:1px solid var(--border-color-primary);border-radius:14px;padding:10px;box-shadow:0 1px 3px rgba(0,0,0,.06)}
.fx-card img{width:100%;aspect-ratio:1;object-fit:cover;border-radius:10px;display:block}
.noimg{aspect-ratio:1;display:flex;align-items:center;justify-content:center;border-radius:10px;background:var(--background-fill-secondary);font-size:13px;color:var(--body-text-color-subdued)}
.cap{font-size:12px;color:var(--body-text-color-subdued);margin:6px 0 2px}
.chip{display:inline-block;color:#fff;font-weight:600;font-size:13px;padding:3px 10px;border-radius:999px;margin-top:8px}
.bar{height:6px;background:var(--background-fill-secondary);border-radius:6px;margin-top:8px;overflow:hidden}
.bar span{display:block;height:100%;border-radius:6px}
.pct{font-size:11.5px;color:var(--body-text-color-subdued);margin-top:4px}
.truth{font-size:12px;margin-top:6px;font-weight:600}.truth.ok{color:#16a34a}.truth.bad{color:#dc2626}
.fx-h{margin:16px 0 4px}
.acc{padding:8px 12px;border-radius:10px;background:rgba(79,70,229,.1);font-size:13.5px;display:inline-block;margin:4px 0}
.acc.big{font-size:15px;margin-bottom:8px}
.note{padding:12px 14px;border-radius:10px;font-size:14px}
.note.warn{background:rgba(245,158,11,.14);border:1px solid rgba(245,158,11,.5)}
.hm{overflow-x:auto;margin-top:8px}.hm table{border-collapse:collapse;font-size:12px;width:100%}
.hm th,.hm td{padding:5px 7px;text-align:center;border:1px solid var(--border-color-primary)}
.hm th{background:var(--background-fill-secondary);font-weight:600;white-space:nowrap}
details summary{cursor:pointer;font-size:13.5px;color:var(--body-text-color-subdued);margin-top:6px}
"""
ABOUT = f"""
### How it works
1. Each photo goes through Py-Feat (Detectorv2), which reads 51 facial movements, 20 action units and 7 emotion scores.
2. The model compares those numbers with the person's other nine photos (each value is also ranked within the person), then scores the ten expressions with a linear model.
3. Each expression is given to exactly one photo, choosing the assignment with the best total score.
### Model
- Weights: [`{REPO}`](https://huggingface.co/{REPO})
- Honest accuracy on people the model never saw: **{(MODEL.cv or 0) * 100:.1f}%** (about {MODEL.n_people} unique people in the data, 10 expressions, chance is 10%).
- The hardest pairs are sad vs hopelessness and scepticism vs uncertainty.
### Use it well
- Use ten photos of the **same person**, one photo per expression, face clearly visible.
- It matches each expression once, so it works on a full set. One photo alone will not give a meaningful answer.
- Photos are processed in memory and not stored.
"""
with gr.Blocks(title="Face Expression Matcher") as demo:
gr.HTML(f"""Face Expression Matcher
Give it ten photos of one person and it works out which of ten expressions each photo shows.
10 expressionsPy-Feat featuresLinear model from the Hub
Held-out accuracy {(MODEL.cv or 0) * 100:.0f}%
""")
with gr.Tabs():
with gr.Tab("Test with photos"):
with gr.Row():
with gr.Column(scale=5):
gal = gr.Gallery(label=f"Upload {N} photos of one person", file_types=["image"], type="filepath",
columns=5, height=300, interactive=True, object_fit="cover")
with gr.Row():
ex_set = gr.Dropdown(list_sets(), label="Or pick an example set", value=None, scale=3,
visible=bool(list_sets()))
ex_btn = gr.Button("Load example", scale=1, visible=bool(list_sets()))
with gr.Row():
go = gr.Button("Match expressions", variant="primary", size="lg")
clr = gr.ClearButton(value="Clear")
res = gr.HTML()
with gr.Accordion("Table and download", open=False):
tbl = gr.Dataframe(interactive=False)
dl = gr.File(label="predictions csv", interactive=False)
go.click(run_photos, gal, [res, tbl, dl], api_name="match_photos")
ex_btn.click(load_set, ex_set, gal)
clr.add([gal, res, tbl, dl])
with gr.Tab("Test with features csv"):
with gr.Row():
with gr.Column():
up = gr.File(label="features.csv (78 feature columns, 10 rows per person, optional person_id)",
file_types=[".csv"], type="filepath")
with gr.Row():
csvx = gr.Dropdown(list_csvs(), label="Or pick an example", value=None, scale=3, visible=bool(list_csvs()))
csvb = gr.Button("Load example", scale=1, visible=bool(list_csvs()))
go2 = gr.Button("Match expressions", variant="primary", size="lg")
res2 = gr.HTML()
with gr.Accordion("Table and download", open=False):
tbl2 = gr.Dataframe(interactive=False)
dl2 = gr.File(label="predictions csv", interactive=False)
go2.click(run_csv, up, [res2, tbl2, dl2], api_name="match_csv")
csvb.click(pick_csv, csvx, up)
with gr.Tab("About the model"):
gr.Markdown(ABOUT)
demo.queue(max_size=16, default_concurrency_limit=2)
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)), css=CSS,
theme=gr.themes.Soft(primary_hue="indigo", secondary_hue="pink", radius_size="lg"))