Spaces:
Running
Running
File size: 26,996 Bytes
e4f2040 ec7950d e4f2040 ec7950d e4f2040 ec7950d e4f2040 ec7950d e4f2040 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 | import hashlib
from collections import OrderedDict
import gradio as gr
import numpy as np
from models.data_manager import DataManager
from models.face_recognition import _dist_to_confidence
from models.image_processor import image_search_performers
from models.sprite_processor import identify_sprite_performers
class _LRUCache:
def __init__(self, maxsize=3):
self.maxsize = maxsize
self._cache = OrderedDict()
@staticmethod
def _hash_args(*args):
h = hashlib.md5(usedforsecurity=False)
for arg in args:
if arg is None:
h.update(b'\x00')
elif isinstance(arg, bytes):
h.update(arg)
elif isinstance(arg, str):
h.update(arg.encode('utf-8'))
elif isinstance(arg, int):
h.update(str(arg).encode())
elif hasattr(arg, 'tobytes'):
h.update(arg.tobytes())
else:
h.update(str(arg).encode())
return h.digest()
def get(self, *args):
key = self._hash_args(*args)
if key in self._cache:
self._cache.move_to_end(key)
return self._cache[key]
return None
def put(self, value, *args):
key = self._hash_args(*args)
self._cache[key] = value
self._cache.move_to_end(key)
while len(self._cache) > self.maxsize:
self._cache.popitem(last=False)
_COUNTRY_FLAGS = {
'AD': '๐ฆ๐ฉ', 'AE': '๐ฆ๐ช', 'AF': '๐ฆ๐ซ', 'AG': '๐ฆ๐ฌ', 'AI': '๐ฆ๐ฎ', 'AL': '๐ฆ๐ฑ', 'AM': '๐ฆ๐ฒ', 'AO': '๐ฆ๐ด',
'AQ': '๐ฆ๐ถ', 'AR': '๐ฆ๐ท', 'AS': '๐ฆ๐ธ', 'AT': '๐ฆ๐น', 'AU': '๐ฆ๐บ', 'AW': '๐ฆ๐ผ', 'AX': '๐ฆ๐ฝ', 'AZ': '๐ฆ๐ฟ',
'BA': '๐ง๐ฆ', 'BB': '๐ง๐ง', 'BD': '๐ง๐ฉ', 'BE': '๐ง๐ช', 'BF': '๐ง๐ซ', 'BG': '๐ง๐ฌ', 'BH': '๐ง๐ญ', 'BI': '๐ง๐ฎ',
'BJ': '๐ง๐ฏ', 'BL': '๐ง๐ฑ', 'BM': '๐ง๐ฒ', 'BN': '๐ง๐ณ', 'BO': '๐ง๐ด', 'BQ': '๐ง๐ถ', 'BR': '๐ง๐ท', 'BS': '๐ง๐ธ',
'BT': '๐ง๐น', 'BV': '๐ง๐ป', 'BW': '๐ง๐ผ', 'BY': '๐ง๐พ', 'BZ': '๐ง๐ฟ', 'CA': '๐จ๐ฆ', 'CC': '๐จ๐จ', 'CD': '๐จ๐ฉ',
'CF': '๐จ๐ซ', 'CG': '๐จ๐ฌ', 'CH': '๐จ๐ญ', 'CI': '๐จ๐ฎ', 'CK': '๐จ๐ฐ', 'CL': '๐จ๐ฑ', 'CM': '๐จ๐ฒ', 'CN': '๐จ๐ณ',
'CO': '๐จ๐ด', 'CR': '๐จ๐ท', 'CU': '๐จ๐บ', 'CV': '๐จ๐ป', 'CW': '๐จ๐ผ', 'CX': '๐จ๐ฝ', 'CY': '๐จ๐พ', 'CZ': '๐จ๐ฟ',
'DE': '๐ฉ๐ช', 'DJ': '๐ฉ๐ฏ', 'DK': '๐ฉ๐ฐ', 'DM': '๐ฉ๐ฒ', 'DO': '๐ฉ๐ด', 'DZ': '๐ฉ๐ฟ', 'EC': '๐ช๐จ', 'EE': '๐ช๐ช',
'EG': '๐ช๐ฌ', 'EH': '๐ช๐ญ', 'ER': '๐ช๐ท', 'ES': '๐ช๐ธ', 'ET': '๐ช๐น', 'FI': '๐ซ๐ฎ', 'FJ': '๐ซ๐ฏ', 'FK': '๐ซ๐ฐ',
'FM': '๐ซ๐ฒ', 'FO': '๐ซ๐ด', 'FR': '๐ซ๐ท', 'GA': '๐ฌ๐ฆ', 'GB': '๐ฌ๐ง', 'GD': '๐ฌ๐ฉ', 'GE': '๐ฌ๐ช', 'GF': '๐ฌ๐ซ',
'GG': '๐ฌ๐ฌ', 'GH': '๐ฌ๐ญ', 'GI': '๐ฌ๐ฎ', 'GL': '๐ฌ๐ฑ', 'GM': '๐ฌ๐ฒ', 'GN': '๐ฌ๐ณ', 'GP': '๐ฌ๐ต', 'GQ': '๐ฌ๐ถ',
'GR': '๐ฌ๐ท', 'GS': '๐ฌ๐ธ', 'GT': '๐ฌ๐น', 'GU': '๐ฌ๐บ', 'GW': '๐ฌ๐ผ', 'GY': '๐ฌ๐พ', 'HK': '๐ญ๐ฐ', 'HM': '๐ญ๐ฒ',
'HN': '๐ญ๐ณ', 'HR': '๐ญ๐ท', 'HT': '๐ญ๐น', 'HU': '๐ญ๐บ', 'ID': '๐ฎ๐ฉ', 'IE': '๐ฎ๐ช', 'IL': '๐ฎ๐ฑ', 'IM': '๐ฎ๐ฒ',
'IN': '๐ฎ๐ณ', 'IO': '๐ฎ๐ด', 'IQ': '๐ฎ๐ถ', 'IR': '๐ฎ๐ท', 'IS': '๐ฎ๐ธ', 'IT': '๐ฎ๐น', 'JE': '๐ฏ๐ช', 'JM': '๐ฏ๐ฒ',
'JO': '๐ฏ๐ด', 'JP': '๐ฏ๐ต', 'KE': '๐ฐ๐ช', 'KG': '๐ฐ๐ฌ', 'KH': '๐ฐ๐ญ', 'KI': '๐ฐ๐ฎ', 'KM': '๐ฐ๐ฒ', 'KN': '๐ฐ๐ณ',
'KP': '๐ฐ๐ต', 'KR': '๐ฐ๐ท', 'KW': '๐ฐ๐ผ', 'KY': '๐ฐ๐พ', 'KZ': '๐ฐ๐ฟ', 'LA': '๐ฑ๐ฆ', 'LB': '๐ฑ๐ง', 'LC': '๐ฑ๐จ',
'LI': '๐ฑ๐ฎ', 'LK': '๐ฑ๐ฐ', 'LR': '๐ฑ๐ท', 'LS': '๐ฑ๐ธ', 'LT': '๐ฑ๐น', 'LU': '๐ฑ๐บ', 'LV': '๐ฑ๐ป', 'LY': '๐ฑ๐พ',
'MA': '๐ฒ๐ฆ', 'MC': '๐ฒ๐จ', 'MD': '๐ฒ๐ฉ', 'ME': '๐ฒ๐ช', 'MF': '๐ฒ๐ซ', 'MG': '๐ฒ๐ฌ', 'MH': '๐ฒ๐ญ', 'MK': '๐ฒ๐ฐ',
'ML': '๐ฒ๐ฑ', 'MM': '๐ฒ๐ฒ', 'MN': '๐ฒ๐ณ', 'MO': '๐ฒ๐ด', 'MP': '๐ฒ๐ต', 'MQ': '๐ฒ๐ถ', 'MR': '๐ฒ๐ท', 'MS': '๐ฒ๐ธ',
'MT': '๐ฒ๐น', 'MU': '๐ฒ๐บ', 'MV': '๐ฒ๐ป', 'MW': '๐ฒ๐ผ', 'MX': '๐ฒ๐ฝ', 'MY': '๐ฒ๐พ', 'MZ': '๐ฒ๐ฟ', 'NA': '๐ณ๐ฆ',
'NC': '๐ณ๐จ', 'NE': '๐ณ๐ช', 'NF': '๐ณ๐ซ', 'NG': '๐ณ๐ฌ', 'NI': '๐ณ๐ฎ', 'NL': '๐ณ๐ฑ', 'NO': '๐ณ๐ด', 'NP': '๐ณ๐ต',
'NR': '๐ณ๐ท', 'NU': '๐ณ๐บ', 'NZ': '๐ณ๐ฟ', 'OM': '๐ด๐ฒ', 'PA': '๐ต๐ฆ', 'PE': '๐ต๐ช', 'PF': '๐ต๐ซ', 'PG': '๐ต๐ฌ',
'PH': '๐ต๐ญ', 'PK': '๐ต๐ฐ', 'PL': '๐ต๐ฑ', 'PM': '๐ต๐ฒ', 'PN': '๐ต๐ณ', 'PR': '๐ต๐ท', 'PS': '๐ต๐ธ', 'PT': '๐ต๐น',
'PW': '๐ต๐ผ', 'PY': '๐ต๐พ', 'QA': '๐ถ๐ฆ', 'RE': '๐ท๐ช', 'RO': '๐ท๐ด', 'RS': '๐ท๐ธ', 'RU': '๐ท๐บ', 'RW': '๐ท๐ผ',
'SA': '๐ธ๐ฆ', 'SB': '๐ธ๐ง', 'SC': '๐ธ๐จ', 'SD': '๐ธ๐ฉ', 'SE': '๐ธ๐ช', 'SG': '๐ธ๐ฌ', 'SH': '๐ธ๐ญ', 'SI': '๐ธ๐ฎ',
'SJ': '๐ธ๐ฏ', 'SK': '๐ธ๐ฐ', 'SL': '๐ธ๐ฑ', 'SM': '๐ธ๐ฒ', 'SN': '๐ธ๐ณ', 'SO': '๐ธ๐ด', 'SR': '๐ธ๐ท', 'SS': '๐ธ๐ธ',
'ST': '๐ธ๐น', 'SV': '๐ธ๐ป', 'SX': '๐ธ๐ฝ', 'SY': '๐ธ๐พ', 'SZ': '๐ธ๐ฟ', 'TC': '๐น๐จ', 'TD': '๐น๐ฉ', 'TF': '๐น๐ซ',
'TG': '๐น๐ฌ', 'TH': '๐น๐ญ', 'TJ': '๐น๐ฏ', 'TK': '๐น๐ฐ', 'TL': '๐น๐ฑ', 'TM': '๐น๐ฒ', 'TN': '๐น๐ณ', 'TO': '๐น๐ด',
'TR': '๐น๐ท', 'TT': '๐น๐น', 'TV': '๐น๐ป', 'TW': '๐น๐ผ', 'TZ': '๐น๐ฟ', 'UA': '๐บ๐ฆ', 'UG': '๐บ๐ฌ', 'UM': '๐บ๐ฒ',
'US': '๐บ๐ธ', 'UY': '๐บ๐พ', 'UZ': '๐บ๐ฟ', 'VA': '๐ป๐ฆ', 'VC': '๐ป๐จ', 'VE': '๐ป๐ช', 'VG': '๐ป๐ฌ', 'VI': '๐ป๐ฎ',
'VN': '๐ป๐ณ', 'VU': '๐ป๐บ', 'WF': '๐ผ๐ซ', 'WS': '๐ผ๐ธ', 'YE': '๐พ๐ช', 'YT': '๐พ๐น', 'ZA': '๐ฟ๐ฆ', 'ZM': '๐ฟ๐ฒ',
'ZW': '๐ฟ๐ผ',
}
class WebInterface:
def __init__(self, data_manager: DataManager):
self.data_manager = data_manager
self._img_cache = _LRUCache(maxsize=3)
self._sprite_cache = _LRUCache(maxsize=3)
def get_country_flag(self, country_code):
if not country_code or len(country_code) != 2:
return ""
return _COUNTRY_FLAGS.get(country_code.upper(), "")
def multiple_image_search(self, img, results):
cached = self._img_cache.get(img, results)
if cached is not None:
return cached
try:
result = image_search_performers(img, self.data_manager, results)
self._img_cache.put(result, img, results)
return result
except ValueError as e:
if "No faces found" in str(e):
return {"error": "No faces detected in the uploaded image. Please try uploading an image with visible faces."}
else:
raise e
def format_results_for_visual_display(self, json_results):
if not json_results:
return "<p>No faces detected or no matches found.</p>"
if isinstance(json_results, dict) and "error" in json_results:
return f"""
<div class="performer-card">
<div class="face-info">
<h3 style="color: #ff6b6b;">Error</h3>
<p>{json_results['error']}</p>
</div>
</div>
"""
html_parts = []
html_parts.append("""
<style>
body, .gradio-container {
background-color: #1e1e1e !important;
color: #d4d4d4 !important;
}
.performer-card {
border: 1px solid #404040;
border-radius: 16px;
padding: 24px;
margin: 16px 0;
background: #2d2d2d;
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
color: #d4d4d4;
}
.face-info {
background: #3c3c3c;
padding: 12px 16px;
border-radius: 10px;
margin-bottom: 24px;
border: 1px solid #4a4a4a;
display: flex;
align-items: center;
gap: 16px;
}
.face-info-content {
flex: 1;
}
.face-info h3 {
color: #ffffff;
margin: 0 0 4px 0;
font-size: 1.1em;
}
.face-info p {
color: #cccccc;
margin: 2px 0;
font-size: 0.9em;
}
.face-info p strong {
color: #9cdcfe;
}
.detected-face img {
width: 72px;
height: 72px;
border-radius: 8px;
object-fit: cover;
border: 2px solid #569cd6;
box-shadow: 0 2px 8px rgba(0,0,0,0.3);
flex-shrink: 0;
}
.performer-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 24px;
margin-top: 8px;
}
.performer-item {
border: 1px solid #4a4a4a;
border-radius: 16px;
padding: 0;
background: #333333;
transition: all 0.3s ease;
box-shadow: 0 2px 8px rgba(0,0,0,0.2);
display: flex;
flex-direction: column;
overflow: hidden;
}
.performer-item:hover {
border-color: #569cd6;
box-shadow: 0 8px 24px rgba(0,0,0,0.5);
transform: translateY(-4px);
}
.performer-image-wrap {
width: 100%;
background: #2a2a2a;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
}
.performer-image {
width: 100%;
max-height: 280px;
object-fit: cover;
object-position: top;
display: block;
border-bottom: 1px solid #4a4a4a;
transition: transform 0.4s ease;
}
.performer-image:hover {
transform: scale(1.04);
}
.performer-body {
padding: 16px;
display: flex;
flex-direction: column;
gap: 8px;
}
.performer-header {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
.performer-name {
color: #ffffff;
margin: 0;
font-size: 1.15em;
font-weight: 600;
line-height: 1.3;
}
.performer-name a {
color: #569cd6;
text-decoration: none;
transition: color 0.3s ease;
}
.performer-name a:hover {
color: #9cdcfe;
text-decoration: underline;
}
.performer-country {
color: #999999;
font-size: 0.85em;
margin-left: auto;
}
.country-flag {
font-size: 1.1em;
margin-right: 4px;
vertical-align: middle;
}
.confidence-bar {
background: #404040;
border-radius: 8px;
overflow: hidden;
height: 24px;
margin: 4px 0 0 0;
border: 1px solid #4a4a4a;
width: 100%;
}
.confidence-fill {
height: 100%;
transition: width 0.5s ease;
text-align: center;
line-height: 24px;
color: white;
font-size: 12px;
font-weight: bold;
text-shadow: 0 1px 2px rgba(0,0,0,0.5);
}
.high-confidence {
background: linear-gradient(135deg, #4caf50, #66bb6a);
}
.medium-confidence {
background: linear-gradient(135deg, #ff9800, #ffb74d);
}
.low-confidence {
background: linear-gradient(135deg, #f44336, #ef5350);
}
.source-badge {
display: inline-block;
width: 18px;
height: 18px;
border-radius: 50%;
text-align: center;
line-height: 18px;
font-size: 10px;
font-weight: 700;
color: #fff;
vertical-align: middle;
cursor: help;
}
.gender-badge {
display: inline-block;
padding: 2px 10px;
border-radius: 10px;
font-size: 0.72em;
font-weight: 600;
letter-spacing: 0.02em;
vertical-align: middle;
border: 1px solid transparent;
}
.gender-female {
background: rgba(220, 120, 200, 0.18);
color: #e8a8d8;
border-color: rgba(220, 120, 200, 0.35);
}
.gender-male {
background: rgba(100, 160, 230, 0.18);
color: #9cc2ee;
border-color: rgba(100, 160, 230, 0.35);
}
.gender-non-binary {
background: rgba(120, 210, 130, 0.18);
color: #a8e0b0;
border-color: rgba(120, 210, 130, 0.35);
}
.gender-transgender-female {
background: rgba(220, 140, 200, 0.12);
color: #d8a8c8;
border-color: rgba(220, 140, 200, 0.28);
}
.gender-transgender-male {
background: rgba(100, 160, 230, 0.12);
color: #a8c0e0;
border-color: rgba(100, 160, 230, 0.28);
}
.source-stashdb { background: #4a6fa5; }
.source-javstash { background: #c0392b; }
.source-fansdb { background: #27ae60; }
</style>
""")
for i, face_result in enumerate(json_results):
face_confidence = face_result['confidence']
performers = face_result['performers']
face_image_b64 = f"data:image/jpeg;base64,{face_result['image']}"
html_parts.append(f"""
<div class="performer-card">
<div class="face-info">
<div class="detected-face">
<img src="{face_image_b64}" alt="Detected Face {i+1}">
</div>
<div class="face-info-content">
<h3>Face {i+1}</h3>
<p><strong>Detection:</strong> {face_confidence:.1%} | <strong>Matches:</strong> {len(performers)}</p>
</div>
</div>
""")
if performers:
html_parts.append('<div class="performer-grid">')
for performer in performers:
confidence_class = "high-confidence" if performer['confidence'] >= 80 else "medium-confidence" if performer['confidence'] >= 60 else "low-confidence"
country_code = performer.get('country', '')
country_flag = self.get_country_flag(country_code)
country_display = f"{country_flag} {country_code}" if country_flag else (country_code if country_code else 'Unknown')
source = performer.get('source', '')
source_badge = ''
if source:
initial = source[0].upper()
source_badge = f'<span class="source-badge source-{source}" title="{source}">{initial}</span>'
gender_raw = performer.get('gender') or ''
gender_badge = ''
if gender_raw:
gender_key = gender_raw.lower().replace('_', '-')
gender_display = gender_raw.lower().replace('_', ' ').title()
if gender_key == 'non-binary':
gender_display = 'Non-binary'
gender_badge = f'<span class="gender-badge gender-{gender_key}">{gender_display}</span>'
html_parts.append(f"""
<div class="performer-item">
<div class="performer-image-wrap">
<img src="{performer['image']}" alt="{performer['name']}" class="performer-image" onerror="this.style.display='none'">
</div>
<div class="performer-body">
<div class="performer-header">
<h4 class="performer-name"><a href="{performer['performer_url']}" target="_blank">{performer['name']}</a></h4>
{source_badge}
{gender_badge}
<span class="performer-country"><span class="country-flag">{country_flag}</span>{country_code if country_code else 'Unknown'}</span>
</div>
<div class="confidence-bar">
<div class="confidence-fill {confidence_class}" style="width: {performer['confidence']}%">
{performer['confidence']}%
</div>
</div>
</div>
</div>
""")
html_parts.append('</div>')
else:
html_parts.append('<p><em>No performer matches found for this face.</em></p>')
html_parts.append('</div>')
return ''.join(html_parts)
def multiple_image_search_with_visual(self, img, results):
"""Run face search and return HTML for visual display."""
try:
json_results = self.multiple_image_search(img, results)
return self.format_results_for_visual_display(json_results)
except Exception as e:
return f"<div class='performer-card'><h3>Error</h3><p>{str(e)}</p></div>"
def search_by_vector(self, payload):
"""Search the AdaFace index directly with a raw 512-dim embedding.
Expects payload = {"embedding": [512 floats], "top_k": 5}.
Skips detection and embedding generation entirely.
"""
if not isinstance(payload, dict):
return {"error": "Payload must be a JSON object: {\"embedding\": [512 floats], \"top_k\": 5}"}
embedding = payload.get("embedding")
if embedding is None:
return {"error": "Missing 'embedding' field."}
try:
emb = np.asarray(embedding, dtype=np.float32)
except (TypeError, ValueError):
return {"error": "'embedding' must be an array of 512 numbers."}
if emb.ndim != 1 or emb.shape[0] != 512:
return {"error": f"'embedding' must have exactly 512 dimensions, got {emb.size}."}
norm = float(np.linalg.norm(emb))
if norm < 1e-12:
return {"error": "'embedding' must be a non-zero vector."}
emb = emb / norm
try:
top_k = int(payload.get("top_k", 5))
except (TypeError, ValueError):
return {"error": "'top_k' must be an integer."}
top_k = max(1, min(top_k, 50))
ids, dists = self.data_manager.query_adaface_index(emb, top_k)
performers = []
for pid, dist in zip(ids, dists):
info = self.data_manager.get_performer_info(pid, _dist_to_confidence(dist), dist)
if info is not None:
performers.append(info)
return {"performers": performers, "count": len(performers)}
def _create_vector_search_interface(self):
"""Create the raw-vector JSON API search interface"""
with gr.Blocks() as interface:
gr.Markdown("# Vector Search API")
gr.Markdown("Search with a raw 512-dim AdaFace embedding (no image upload).")
with gr.Row():
with gr.Column():
payload_input = gr.JSON(
label="Request",
value={"embedding": [0.0] * 512, "top_k": 5},
)
search_btn = gr.Button("Search")
with gr.Column():
json_output = gr.JSON(label="JSON Results")
search_btn.click(
fn=self.search_by_vector,
inputs=[payload_input],
outputs=json_output,
api_name="search_by_vector"
)
return interface
def _create_json_search_interface(self):
"""Create the JSON API search interface"""
with gr.Blocks() as interface:
gr.Markdown("# Face Recognition API")
gr.Markdown("Upload an image and get JSON results - perfect for API integration.")
with gr.Row():
with gr.Column():
img_input = gr.Image(type="pil")
results_count = gr.Slider(
label="Top matches",
minimum=3,
maximum=50,
value=5,
step=1
)
search_btn = gr.Button("Search")
with gr.Column():
json_output = gr.JSON(label="JSON Results")
search_btn.click(
fn=self.multiple_image_search,
inputs=[img_input, results_count],
outputs=json_output,
api_name="multiple_image_search"
)
return interface
def identify_sprite_performers_wrapper(self, sprite_img, vtt_file, threshold):
if sprite_img is None:
yield {"error": "Please upload a sprite image."}
return
if vtt_file is None:
yield {"error": "Please upload a VTT file."}
return
try:
if hasattr(vtt_file, 'read'):
vtt_text = vtt_file.read().decode('utf-8')
else:
with open(vtt_file, 'r', encoding='utf-8') as f:
vtt_text = f.read()
except Exception as e:
yield {"error": f"Failed to read VTT file: {e}"}
return
cached = self._sprite_cache.get(sprite_img, vtt_text, threshold)
if cached is not None:
yield cached
return
gen = identify_sprite_performers(
sprite_img, vtt_text, self.data_manager,
detection_threshold=threshold / 100.0,
)
try:
final = None
for item in gen:
if isinstance(item, tuple) and len(item) == 2:
progress_val, desc = item
yield {"progress": progress_val, "desc": desc}
else:
final = item
yield item
return
except ValueError as e:
yield {"error": str(e)}
finally:
if final is not None:
self._sprite_cache.put(final, sprite_img, vtt_text, threshold)
def _create_sprite_search_interface(self):
with gr.Blocks() as interface:
gr.Markdown("# Sprite/VTT Batch Face Identification")
gr.Markdown("Upload a scene sprite image and its VTT file to identify all performers across the entire scene.")
with gr.Row():
with gr.Column():
sprite_input = gr.Image(type="pil")
vtt_input = gr.File(label="VTT File", file_types=[".vtt"])
threshold = gr.Slider(
label="Detection threshold",
minimum=1,
maximum=100,
value=50,
step=1,
)
search_btn = gr.Button("Identify Performers")
with gr.Column():
json_output = gr.JSON(label="Identification Results")
search_btn.click(
fn=self.identify_sprite_performers_wrapper,
inputs=[sprite_input, vtt_input, threshold],
outputs=json_output,
api_name="identify_sprite_performers",
)
return interface
def _create_visual_search_interface(self):
with gr.Blocks() as interface:
gr.Markdown("# Who is in the photo?")
gr.Markdown("Upload an image of a person(s) and we'll show you who it is with photos and details.")
with gr.Row():
with gr.Column():
img_input = gr.Image(type="pil")
results_count = gr.Slider(
label="Top matches",
minimum=3,
maximum=50,
value=5,
step=1
)
search_btn = gr.Button("Search")
with gr.Column():
performer_info = gr.HTML(
label="Performer Information",
value="<p>Upload an image and click search to see results.</p>"
)
search_btn.click(
fn=self.multiple_image_search_with_visual,
inputs=[img_input, results_count],
outputs=[performer_info],
api_name="multiple_image_search_with_visual"
)
return interface
def launch(self, server_name="0.0.0.0", server_port=7860, share=True):
with gr.Blocks(
css="""
.gradio-container {
background-color: #1e1e1e !important;
color: #d4d4d4 !important;
}
.dark {
--background-fill-primary: #2d2d2d;
--background-fill-secondary: #3c3c3c;
--border-color-primary: #404040;
--block-title-text-color: #ffffff;
--body-text-color: #d4d4d4;
}
"""
) as demo:
with gr.Tabs():
with gr.TabItem("Visual Search"):
self._create_visual_search_interface()
with gr.TabItem("JSON API"):
self._create_json_search_interface()
with gr.TabItem("Sprite Search"):
self._create_sprite_search_interface()
with gr.TabItem("Vector Search"):
self._create_vector_search_interface()
@demo.app.middleware("http")
async def add_cors(request, call_next):
response = await call_next(request)
response.headers["Access-Control-Allow-Origin"] = "*"
response.headers["Access-Control-Allow-Methods"] = "*"
response.headers["Access-Control-Allow-Headers"] = "*"
response.headers["Access-Control-Allow-Credentials"] = "true"
return response
demo.queue().launch(server_name=server_name, server_port=server_port, share=share, ssr_mode=False)
|