amisima commited on
Commit
4c3d5c2
·
verified ·
1 Parent(s): ddf1387

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +177 -95
app.py CHANGED
@@ -11,6 +11,7 @@ import warnings
11
  import time
12
  import gc
13
  import uuid
 
14
  from tqdm import tqdm
15
  import cv2
16
  import numpy as np
@@ -483,6 +484,109 @@ _FACE_CASCADES = None
483
  _FACE_DETECT_MAX_SIDE = 1600
484
  _YUNET_LOCAL = os.environ.get("YUNET_ONNX", "").strip()
485
  _YUNET_PATH = "unset"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
486
 
487
 
488
  def _to_pil_rgb(img):
@@ -708,7 +812,7 @@ def _landmarks_from_eyes(eyes):
708
  return None
709
 
710
 
711
- def _detect_face(img_rgb):
712
  """(box, landmarks5) for the dominant face, or (None, None).
713
 
714
  box = (x, y, w, h) in full-image pixels. landmarks5 = float32 5x2 in YuNet
@@ -754,6 +858,8 @@ def _detect_face(img_rgb):
754
  print("[identity] yunet failed (%s); haar fallback"
755
  % type(error).__name__, flush=True)
756
 
 
 
757
  cascades = _load_face_cascades()
758
  if not any(c is not None for c in cascades):
759
  return None, None
@@ -882,21 +988,6 @@ def _guarded_affine(src, dst):
882
  return None
883
 
884
 
885
- def _mirror_reference(ref_img, ref_lm):
886
- """The locked picture flipped left to right, landmarks and all.
887
-
888
- Half of all pose mismatches are simply the head turned the other way, and a
889
- mirrored copy of the lock costs nothing to try.
890
- """
891
- try:
892
- flipped = np.ascontiguousarray(ref_img[:, ::-1])
893
- marks = np.asarray(ref_lm, dtype=np.float32).copy()
894
- marks[:, 0] = (ref_img.shape[1] - 1) - marks[:, 0]
895
- return flipped, marks[[1, 0, 2, 4, 3]]
896
- except Exception:
897
- return None, None
898
-
899
-
900
  def _fit_score(face_rgb, base_rgb, weight):
901
  """How badly a warped candidate disagrees with the frame, 0 (same) to 1.
902
 
@@ -914,14 +1005,14 @@ def _fit_score(face_rgb, base_rgb, weight):
914
  return 1.0
915
 
916
 
917
- def _face_mask(patch_w, patch_h, landmarks=None, eye_relief=0.55):
918
  """Feathered mask over the patch, oriented by the eye line.
919
 
920
  Without landmarks: an axis-aligned ellipse, taller than wide so the jaw and
921
  the hairline are covered. With landmarks: the ellipse sits between the eyes
922
  and the mouth and is rotated to the eye-line angle, so it follows a tilted
923
  head, and two soft holes are carved at the eyes - the generated gaze and the
924
- blinks of the lip-sync survive while identity still comes from around them.
925
  """
926
  mask = np.zeros((patch_h, patch_w), dtype=np.float32)
927
  eyes = None
@@ -966,33 +1057,31 @@ def _face_mask(patch_w, patch_h, landmarks=None, eye_relief=0.55):
966
 
967
  k = max(3, (min(patch_w, patch_h) // 10) | 1)
968
  mask = cv2.GaussianBlur(mask, (k, k), 0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
969
  return np.clip(mask, 0.0, 1.0)
970
 
971
 
972
  def _images_similar(a, b):
973
- """Cheap 'same face?' check.
974
-
975
- The whole-frame signature is kept as a fast path, but the decision is made
976
- on the face regions: between clips the scene around the face moves, the
977
- face itself is the thing that must not.
978
- """
979
  if a is None or b is None:
980
  return False
981
  try:
982
- if a.size == b.size:
983
- sa = np.asarray(a.convert("L").resize((16, 16)), dtype=np.float32)
984
- sb = np.asarray(b.convert("L").resize((16, 16)), dtype=np.float32)
985
- if float(np.abs(sa - sb).mean()) < 2.0:
986
- return True
987
- box_a, _ = _detect_face(np.asarray(a))
988
- box_b, _ = _detect_face(np.asarray(b))
989
- if box_a is None or box_b is None:
990
- return False
991
- pa = a.crop((box_a[0], box_a[1], box_a[0] + box_a[2], box_a[1] + box_a[3]))
992
- pb = b.crop((box_b[0], box_b[1], box_b[0] + box_b[2], box_b[1] + box_b[3]))
993
- sa = np.asarray(pa.convert("L").resize((16, 16)), dtype=np.float32)
994
- sb = np.asarray(pb.convert("L").resize((16, 16)), dtype=np.float32)
995
- return float(np.abs(sa - sb).mean()) < 4.0
996
  except Exception:
997
  return False
998
 
@@ -1000,11 +1089,12 @@ def _images_similar(a, b):
1000
  def _blend_identity(start_img, identity_img, strength, quiet=False, chain_index=0):
1001
  """Pull the face in `start_img` back toward the face in `identity_img`.
1002
 
1003
- Returns (image, anchored). The locked face is warped onto the frame's head
1004
- pose from five landmarks (rotation + scale + position, no stretch), colour
1005
  matched in LAB with a clamped gain, sharpness matched to the frame and then
1006
- blended through a mask oriented by the eye line that leaves the eyes mostly
1007
- alone. A no-op (start_img, False) when the lock is off, when a face cannot
 
1008
  be found in either picture, or when the start frame already is the locked
1009
  picture (the first generation of a chain).
1010
  """
@@ -1024,7 +1114,9 @@ def _blend_identity(start_img, identity_img, strength, quiet=False, chain_index=
1024
 
1025
  if _images_similar(base, ref):
1026
  _say("[identity] the start frame IS the locked picture - nothing to anchor", flush=True)
1027
- return start_img, {"ok": False, "note": "the start frame already is the locked face"}
 
 
1028
 
1029
  base_np = np.asarray(base).copy()
1030
  ref_np = np.ascontiguousarray(np.asarray(ref))
@@ -1035,6 +1127,9 @@ def _blend_identity(start_img, identity_img, strength, quiet=False, chain_index=
1035
  _say("[identity] no face found in the frame or in the lock - not anchored", flush=True)
1036
  return start_img, {"ok": False, "note": "no face found in %s" % which}
1037
 
 
 
 
1038
  def _sane(box, img):
1039
  return (box[2] * box[3]) < 0.72 * float(img.width) * float(img.height)
1040
 
@@ -1071,14 +1166,9 @@ def _blend_identity(start_img, identity_img, strength, quiet=False, chain_index=
1071
  mask = _face_mask(patch_w, patch_h, landmarks=landmarks)
1072
  weight = mask > 0.35
1073
 
1074
- # Four ways to put the locked face on this head - rotation-and-scale
1075
- # or a guarded affine, each on the picture as it is and on its
1076
- # mirror. They are all cheap, so the one that actually lands on the
1077
- # frame's face is chosen by measurement rather than by assumption.
1078
  sources = [("", ref_np, np.asarray(ref_lm, dtype=np.float32))]
1079
- m_img, m_lm = _mirror_reference(ref_np, ref_lm)
1080
- if m_img is not None:
1081
- sources.append((" mirrored", m_img, m_lm))
1082
 
1083
  best_score = None
1084
  for tag, img, marks in sources:
@@ -1221,13 +1311,22 @@ def _blend_identity(start_img, identity_img, strength, quiet=False, chain_index=
1221
  # drift, where a hard pull only smears the two together.
1222
  trim = float(np.clip(1.0 - (mismatch - 0.09) * 7.0, 0.15, 1.0))
1223
  used *= need * trim
 
 
 
 
 
 
 
1224
  if used < 0.02:
1225
- _say("[identity] the face still matches (%.3f) - left alone" % mismatch,
1226
  flush=True)
1227
  return start_img, {
1228
- "ok": True, "note": "", "mismatch": float(mismatch), "used": 0.0,
1229
  "asked": float(strength), "aligned": landmarks is not None,
1230
  "fit": fit_name, "untouched": True,
 
 
1231
  }
1232
  except Exception:
1233
  mismatch = 0.0
@@ -1264,7 +1363,7 @@ def _blend_identity(start_img, identity_img, strength, quiet=False, chain_index=
1264
  return Image.fromarray(out_np), {
1265
  "ok": True, "note": "", "mismatch": float(mismatch), "used": float(used),
1266
  "asked": float(strength), "aligned": landmarks is not None,
1267
- "fit": fit_name,
1268
  }
1269
  except Exception as error:
1270
  _say("[identity] anchor failed, frame kept as-is: %s" % error, flush=True)
@@ -1279,8 +1378,8 @@ for _gpu_fn_name in ("run_inference", "_mmaudio_run", "_hunyuan_run"):
1279
  print(f"[warning] {_gpu_fn_name} is not wrapped for ZeroGPU - it will try to use the "
1280
  f"card from the main process and fail", flush=True)
1281
 
1282
- print("[identity] identity lock v2 loaded - landmark alignment, eye-line mask, "
1283
- "LAB colour match", flush=True)
1284
 
1285
  # Fetch the detector while the Space is starting rather than during the first
1286
  # generation. A ZeroGPU pass is minted when the browser sends the request and it
@@ -1289,6 +1388,7 @@ print("[identity] identity lock v2 loaded - landmark alignment, eye-line mask, "
1289
  try:
1290
  _yunet_path()
1291
  _load_face_cascades()
 
1292
  except Exception as _warmup_error: # noqa: BLE001
1293
  print(f"[identity] detector warm-up skipped: {_warmup_error}", flush=True)
1294
 
@@ -1622,29 +1722,16 @@ def generate_video(
1622
  identity_info = ""
1623
  if identity_report is not None:
1624
  if identity_report.get("ok"):
1625
- match = max(0.0, min(1.0, 1.0 - float(identity_report.get("mismatch", 0.0)) * 4.0))
1626
  used_pull = float(identity_report.get("used", 0.0))
1627
  asked_pull = float(identity_report.get("asked", used_pull))
1628
- if match >= 0.75:
1629
- verdict = "good match"
1630
- elif match >= 0.5:
1631
- verdict = "fair match"
1632
- else:
1633
- verdict = "poor match - use a lock photo from the same angle"
1634
- if identity_report.get("untouched"):
1635
- eased = " &middot; already matches, left alone"
1636
- elif used_pull >= asked_pull - 0.005:
1637
- eased = ""
1638
- else:
1639
- eased = f", eased to {used_pull:.2f}"
1640
  fit = identity_report.get("fit", "")
1641
- if fit and fit != "box":
1642
- eased += f" &middot; {fit}"
1643
- if not identity_report.get("aligned", True):
1644
- eased += ", not aligned"
1645
  identity_info = (
1646
- f"<span>&#128274; face anchored &middot; {int(round(match * 100))}% "
1647
- f"{verdict}{eased}</span>"
1648
  )
1649
  else:
1650
  identity_info = (
@@ -4531,19 +4618,13 @@ def check_identity_photo(lock_image, start_image):
4531
  note = (report or {}).get("note", "it cannot be used with this starting picture")
4532
  return f"<div class='status-idle'>&#10007; Cannot be used: {note}.</div>"
4533
 
4534
- match = max(0.0, min(1.0, 1.0 - float(report.get("mismatch", 0.0)) * 4.0))
4535
- pct = int(round(match * 100))
4536
- if match >= 0.75:
4537
- return (f"<div class='status-ok'>&#10003; These two go together well ({pct}%). "
4538
- "Nothing else to set - just generate.</div>")
4539
- if match >= 0.5:
4540
- return (f"<div class='status-ok'>&#10003; Usable ({pct}%), but not a close match. "
4541
- "A photo taken from the same angle as your starting picture would be "
4542
- "better. The pull is eased off on its own, so it will not look pasted "
4543
- "on.</div>")
4544
- return (f"<div class='status-idle'>&#9888; Only a {pct}% match - the angle, the light "
4545
- "or the expression is too different. Pick another photo of the same person, "
4546
- "ideally facing the same way as in your starting picture.</div>")
4547
  except Exception as error:
4548
  return f"<div class='status-idle'>Could not check this photo: {type(error).__name__}</div>"
4549
 
@@ -5152,12 +5233,14 @@ with gr.Blocks(delete_cache=(3600, 259200)) as demo:
5152
  with gr.Accordion("🔒 Keep the same face — improved (optional)", open=False):
5153
  gr.Markdown(
5154
  "**In long scenes the face slowly stops looking like the person.** "
5155
- "Drop a photo of that person here and every clip is pulled back "
5156
- "toward it.\n\n"
 
5157
  "Leave it empty and nothing is touched, which is what you want most "
5158
  "of the time. Use a photo where the person faces the same way as in "
5159
- "your starting picture — the line under the box tells you straight "
5160
- "away whether the photo is a good one, before you spend any GPU time."
 
5161
  )
5162
  identity_ref_component = gr.Image(
5163
  type="pil", label="Photo of the person", height=160,
@@ -5167,10 +5250,9 @@ with gr.Blocks(delete_cache=(3600, 259200)) as demo:
5167
  identity_strength_slider = gr.Slider(
5168
  0.0, 1.0, value=0.45, step=0.05,
5169
  label="At most this strong",
5170
- info="You can leave this alone. It is a ceiling, not a fixed amount: "
5171
- "a photo that matches well is used at nearly full strength, and "
5172
- "one that matches badly is eased off on its own. Set it to 0 to "
5173
- "switch the whole thing off.",
5174
  )
5175
 
5176
  prompt_input = gr.Textbox(
 
11
  import time
12
  import gc
13
  import uuid
14
+ import threading
15
  from tqdm import tqdm
16
  import cv2
17
  import numpy as np
 
484
  _FACE_DETECT_MAX_SIDE = 1600
485
  _YUNET_LOCAL = os.environ.get("YUNET_ONNX", "").strip()
486
  _YUNET_PATH = "unset"
487
+ _SFACE = None
488
+ _SFACE_ATTEMPTED = False
489
+ _SFACE_LOCK = threading.RLock()
490
+
491
+
492
+ def _load_identity_recognizer():
493
+ """Optional CPU SFace. Download once, atomically; failure keeps lock usable.
494
+
495
+ SFACE_ONNX can point to an offline copy. No photos leave this process.
496
+ Source/API: https://docs.opencv.org/4.x/d0/dd4/tutorial_dnn_face.html
497
+ """
498
+ global _SFACE, _SFACE_ATTEMPTED
499
+ with _SFACE_LOCK:
500
+ if _SFACE_ATTEMPTED:
501
+ return _SFACE
502
+ _SFACE_ATTEMPTED = True
503
+ if not hasattr(cv2, "FaceRecognizerSF"):
504
+ return None
505
+ name = "face_recognition_sface_2021dec.onnx"
506
+ cache_dir = os.path.join(tempfile.gettempdir(), "wan_identity")
507
+ cached = os.path.join(cache_dir, name)
508
+ candidates = [os.environ.get("SFACE_ONNX", "").strip(),
509
+ os.path.join(os.path.dirname(os.path.abspath(__file__)), name),
510
+ cached]
511
+ for path in candidates:
512
+ try:
513
+ if path and os.path.getsize(path) > 1000000:
514
+ _SFACE = cv2.FaceRecognizerSF.create(path, "")
515
+ return _SFACE
516
+ except Exception:
517
+ continue
518
+ temporary = None
519
+ try:
520
+ import urllib.request
521
+ os.makedirs(cache_dir, exist_ok=True)
522
+ fd, temporary = tempfile.mkstemp(prefix="sface-", suffix=".onnx", dir=cache_dir)
523
+ url = ("https://media.githubusercontent.com/media/opencv/opencv_zoo/main/"
524
+ "models/face_recognition_sface/" + name)
525
+ deadline = time.monotonic() + 40.0
526
+ with os.fdopen(fd, "wb") as out:
527
+ with urllib.request.urlopen(url, timeout=10) as response:
528
+ while True:
529
+ chunk = response.read(1024 * 1024)
530
+ if not chunk:
531
+ break
532
+ out.write(chunk)
533
+ if time.monotonic() > deadline or out.tell() > 60000000:
534
+ raise RuntimeError("SFace download limit reached")
535
+ model = cv2.FaceRecognizerSF.create(temporary, "")
536
+ os.replace(temporary, cached)
537
+ _SFACE = model
538
+ print("[identity] SFace ready (CPU)", flush=True)
539
+ except Exception as error:
540
+ print("[identity] SFace unavailable; using alignment checks (%s)"
541
+ % type(error).__name__, flush=True)
542
+ finally:
543
+ if temporary and os.path.exists(temporary):
544
+ os.remove(temporary)
545
+ return _SFACE
546
+
547
+
548
+ def _identity_cosine(base, base_box, base_lm, ref, ref_box, ref_lm):
549
+ """Unmodified aligned faces only; cosine is a score, not a probability."""
550
+ if base_lm is None or ref_lm is None:
551
+ return None
552
+ # Haar's nose/mouth landmarks are guessed, unsuitable for recognition.
553
+ if not _yunet_path():
554
+ return None
555
+ # Request measured landmarks explicitly, including when YuNet fell back
556
+ # to Haar on just one of the two pictures.
557
+ base_box, base_lm = _detect_face(base, allow_haar=False)
558
+ ref_box, ref_lm = _detect_face(ref, allow_haar=False)
559
+ if base_lm is None or ref_lm is None:
560
+ return None
561
+ model = _load_identity_recognizer()
562
+ if model is None:
563
+ return None
564
+ try:
565
+ with _SFACE_LOCK:
566
+ features = []
567
+ for img, box, marks in ((base, base_box, base_lm), (ref, ref_box, ref_lm)):
568
+ if min(box[2:]) < 48:
569
+ return None
570
+ row = np.concatenate((np.asarray(box, dtype=np.float32),
571
+ np.asarray(marks, dtype=np.float32).reshape(-1),
572
+ np.array([1.0], dtype=np.float32)))
573
+ bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
574
+ aligned = model.alignCrop(bgr, row)
575
+ features.append(model.feature(aligned).copy())
576
+ score = float(model.match(features[0], features[1], cv2.FaceRecognizerSF_FR_COSINE))
577
+ return float(np.clip(score, -1.0, 1.0)) if np.isfinite(score) else None
578
+ except Exception:
579
+ return None
580
+
581
+
582
+ def _identity_status(report):
583
+ """Report input assessment without inventing identity percentages."""
584
+ if report.get("exact"):
585
+ return "same source image; no correction needed"
586
+ score = report.get("identity_cosine")
587
+ if score is not None:
588
+ return "input face similarity %.3f (SFace; higher is closer, not a percentage)" % score
589
+ return "alignment check only; identity similarity unavailable"
590
 
591
 
592
  def _to_pil_rgb(img):
 
812
  return None
813
 
814
 
815
+ def _detect_face(img_rgb, allow_haar=True):
816
  """(box, landmarks5) for the dominant face, or (None, None).
817
 
818
  box = (x, y, w, h) in full-image pixels. landmarks5 = float32 5x2 in YuNet
 
858
  print("[identity] yunet failed (%s); haar fallback"
859
  % type(error).__name__, flush=True)
860
 
861
+ if not allow_haar:
862
+ return None, None
863
  cascades = _load_face_cascades()
864
  if not any(c is not None for c in cascades):
865
  return None, None
 
988
  return None
989
 
990
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
991
  def _fit_score(face_rgb, base_rgb, weight):
992
  """How badly a warped candidate disagrees with the frame, 0 (same) to 1.
993
 
 
1005
  return 1.0
1006
 
1007
 
1008
+ def _face_mask(patch_w, patch_h, landmarks=None, eye_relief=0.55, mouth_relief=0.90):
1009
  """Feathered mask over the patch, oriented by the eye line.
1010
 
1011
  Without landmarks: an axis-aligned ellipse, taller than wide so the jaw and
1012
  the hairline are covered. With landmarks: the ellipse sits between the eyes
1013
  and the mouth and is rotated to the eye-line angle, so it follows a tilted
1014
  head, and two soft holes are carved at the eyes - the generated gaze and the
1015
+ blinks survive. A separate soft mouth exclusion protects speech and smiles.
1016
  """
1017
  mask = np.zeros((patch_h, patch_w), dtype=np.float32)
1018
  eyes = None
 
1057
 
1058
  k = max(3, (min(patch_w, patch_h) // 10) | 1)
1059
  mask = cv2.GaussianBlur(mask, (k, k), 0)
1060
+ if eyes is not None and mouth_relief > 0:
1061
+ # Multiplicative, after feathering: never increase an existing mask.
1062
+ # Five landmarks cannot measure mouth opening, so protect a generous
1063
+ # vertical region as well as the two lip corners.
1064
+ mouth_axis = pts[4] - pts[3]
1065
+ mouth_width = float(np.linalg.norm(mouth_axis))
1066
+ mouth_angle = float(np.arctan2(mouth_axis[1], mouth_axis[0]))
1067
+ yy, xx = np.mgrid[:patch_h, :patch_w].astype(np.float32)
1068
+ dx, dy = xx - mouth[0], yy - mouth[1]
1069
+ along = dx * np.cos(mouth_angle) + dy * np.sin(mouth_angle)
1070
+ across = -dx * np.sin(mouth_angle) + dy * np.cos(mouth_angle)
1071
+ sx = max(4.0, mouth_width * 0.65, eye_dist * 0.32)
1072
+ sy = max(3.0, eye_dist * 0.30)
1073
+ relief = np.exp(-0.5 * ((along / sx) ** 2 + (across / sy) ** 2))
1074
+ mask *= 1.0 - float(np.clip(mouth_relief, 0.0, 1.0)) * relief
1075
  return np.clip(mask, 0.0, 1.0)
1076
 
1077
 
1078
  def _images_similar(a, b):
1079
+ """Exact image fast path. Tiny thumbnails cannot establish identity."""
 
 
 
 
 
1080
  if a is None or b is None:
1081
  return False
1082
  try:
1083
+ return a.size == b.size and np.array_equal(
1084
+ np.asarray(a.convert("RGB")), np.asarray(b.convert("RGB")))
 
 
 
 
 
 
 
 
 
 
 
 
1085
  except Exception:
1086
  return False
1087
 
 
1089
  def _blend_identity(start_img, identity_img, strength, quiet=False, chain_index=0):
1090
  """Pull the face in `start_img` back toward the face in `identity_img`.
1091
 
1092
+ Returns (image, report). The reference is aligned from five landmarks
1093
+ using a similarity or guarded affine transform, colour
1094
  matched in LAB with a clamped gain, sharpness matched to the frame and then
1095
+ blended through a mask protecting the eyes and mouth. The report records
1096
+ whether correction was applied, skipped, or unnecessary. A no-op when the
1097
+ lock is off, when a face cannot
1098
  be found in either picture, or when the start frame already is the locked
1099
  picture (the first generation of a chain).
1100
  """
 
1114
 
1115
  if _images_similar(base, ref):
1116
  _say("[identity] the start frame IS the locked picture - nothing to anchor", flush=True)
1117
+ return start_img, {"ok": True, "exact": True, "untouched": True,
1118
+ "used": 0.0, "asked": float(strength), "mismatch": 0.0,
1119
+ "note": "the start frame is the reference image"}
1120
 
1121
  base_np = np.asarray(base).copy()
1122
  ref_np = np.ascontiguousarray(np.asarray(ref))
 
1127
  _say("[identity] no face found in the frame or in the lock - not anchored", flush=True)
1128
  return start_img, {"ok": False, "note": "no face found in %s" % which}
1129
 
1130
+ identity_cosine = _identity_cosine(
1131
+ base_np, base_box, base_lm, ref_np, ref_box, ref_lm)
1132
+
1133
  def _sane(box, img):
1134
  return (box[2] * box[3]) < 0.72 * float(img.width) * float(img.height)
1135
 
 
1166
  mask = _face_mask(patch_w, patch_h, landmarks=landmarks)
1167
  weight = mask > 0.35
1168
 
1169
+ # Preserve left/right facial asymmetry; do not mirror a reference
1170
+ # merely because its lighting gives a lower pixel error.
 
 
1171
  sources = [("", ref_np, np.asarray(ref_lm, dtype=np.float32))]
 
 
 
1172
 
1173
  best_score = None
1174
  for tag, img, marks in sources:
 
1311
  # drift, where a hard pull only smears the two together.
1312
  trim = float(np.clip(1.0 - (mismatch - 0.09) * 7.0, 0.15, 1.0))
1313
  used *= need * trim
1314
+ # SFace only reduces unnecessary pixel correction. These are
1315
+ # conservative blending heuristics, not calibrated identity
1316
+ # thresholds. A low score never overrides the geometry guard
1317
+ # or increases the existing maximum pull.
1318
+ if identity_cosine is not None:
1319
+ identity_need = float(np.clip((0.80 - identity_cosine) / 0.35, 0.0, 1.0))
1320
+ used *= identity_need
1321
  if used < 0.02:
1322
+ _say("[identity] correction below minimum (pixel error %.3f) - left alone" % mismatch,
1323
  flush=True)
1324
  return start_img, {
1325
+ "ok": True, "mismatch": float(mismatch), "used": 0.0,
1326
  "asked": float(strength), "aligned": landmarks is not None,
1327
  "fit": fit_name, "untouched": True,
1328
+ "identity_cosine": identity_cosine,
1329
+ "note": "correction below minimum; frame left unchanged",
1330
  }
1331
  except Exception:
1332
  mismatch = 0.0
 
1363
  return Image.fromarray(out_np), {
1364
  "ok": True, "note": "", "mismatch": float(mismatch), "used": float(used),
1365
  "asked": float(strength), "aligned": landmarks is not None,
1366
+ "fit": fit_name, "identity_cosine": identity_cosine,
1367
  }
1368
  except Exception as error:
1369
  _say("[identity] anchor failed, frame kept as-is: %s" % error, flush=True)
 
1378
  print(f"[warning] {_gpu_fn_name} is not wrapped for ZeroGPU - it will try to use the "
1379
  f"card from the main process and fail", flush=True)
1380
 
1381
+ print("[identity] identity lock v3 loaded - SFace assessment, mouth protection, "
1382
+ "no mirrored references", flush=True)
1383
 
1384
  # Fetch the detector while the Space is starting rather than during the first
1385
  # generation. A ZeroGPU pass is minted when the browser sends the request and it
 
1388
  try:
1389
  _yunet_path()
1390
  _load_face_cascades()
1391
+ _load_identity_recognizer()
1392
  except Exception as _warmup_error: # noqa: BLE001
1393
  print(f"[identity] detector warm-up skipped: {_warmup_error}", flush=True)
1394
 
 
1722
  identity_info = ""
1723
  if identity_report is not None:
1724
  if identity_report.get("ok"):
 
1725
  used_pull = float(identity_report.get("used", 0.0))
1726
  asked_pull = float(identity_report.get("asked", used_pull))
1727
+ assessment = _identity_status(identity_report)
1728
+ action = ("start frame left unchanged" if identity_report.get("untouched")
1729
+ else "start frame corrected")
 
 
 
 
 
 
 
 
 
1730
  fit = identity_report.get("fit", "")
1731
+ fit_info = f" &middot; {fit}" if fit else ""
 
 
 
1732
  identity_info = (
1733
+ f"<span>&#128274; {action} &middot; {assessment}"
1734
+ f" &middot; pull {used_pull:.2f} / {asked_pull:.2f}{fit_info}</span>"
1735
  )
1736
  else:
1737
  identity_info = (
 
4618
  note = (report or {}).get("note", "it cannot be used with this starting picture")
4619
  return f"<div class='status-idle'>&#10007; Cannot be used: {note}.</div>"
4620
 
4621
+ assessment = _identity_status(report)
4622
+ if report.get("exact"):
4623
+ return ("<div class='status-ok'>&#10003; Same source image. "
4624
+ "The first frame needs no correction; continuation frames will be checked.</div>")
4625
+ return (f"<div class='status-ok'>&#10003; Face alignment is usable; {assessment}. "
4626
+ "Use a reference from a similar angle. This checks the starting image, "
4627
+ "not identity throughout the finished video.</div>")
 
 
 
 
 
 
4628
  except Exception as error:
4629
  return f"<div class='status-idle'>Could not check this photo: {type(error).__name__}</div>"
4630
 
 
5233
  with gr.Accordion("🔒 Keep the same face — improved (optional)", open=False):
5234
  gr.Markdown(
5235
  "**In long scenes the face slowly stops looking like the person.** "
5236
+ "Drop a photo of that person here. Before each clip, its starting "
5237
+ "frame is checked and gently corrected when needed. This cannot "
5238
+ "guarantee the same face throughout the generated clip.\n\n"
5239
  "Leave it empty and nothing is touched, which is what you want most "
5240
  "of the time. Use a photo where the person faces the same way as in "
5241
+ "your starting picture. Eyes and mouth are protected to preserve "
5242
+ "expression. Face similarity is checked locally when available; "
5243
+ "otherwise the app uses alignment checks."
5244
  )
5245
  identity_ref_component = gr.Image(
5246
  type="pil", label="Photo of the person", height=160,
 
5250
  identity_strength_slider = gr.Slider(
5251
  0.0, 1.0, value=0.45, step=0.05,
5252
  label="At most this strong",
5253
+ info="Maximum correction, reduced automatically for a close face match "
5254
+ "or difficult alignment. Continuations are additionally capped "
5255
+ "at 0.28 to limit ghosting. Set to 0 to switch it off.",
 
5256
  )
5257
 
5258
  prompt_input = gr.Textbox(