Spaces:
Running
Running
File size: 45,071 Bytes
159d2da 338ce2e e5e7739 11438c4 e5e7739 338ce2e e5e7739 338ce2e e5e7739 159d2da dd65a21 159d2da 338ce2e 159d2da 6521c53 1423d71 6521c53 159d2da 4a355c8 338ce2e 620638a 338ce2e 873ae84 620638a 873ae84 620638a 873ae84 620638a 873ae84 620638a 873ae84 620638a 338ce2e 4a355c8 338ce2e 4a355c8 338ce2e bbbff8b 620638a bbbff8b 873ae84 bbbff8b 338ce2e 4a355c8 338ce2e 4a355c8 338ce2e e5e7739 159d2da 4a355c8 aeee576 4a355c8 aeee576 4a355c8 aeee576 4a355c8 aeee576 4a355c8 aeee576 4a355c8 aeee576 4a355c8 aeee576 4a355c8 aeee576 4a355c8 338ce2e aeee576 4a355c8 aeee576 4a355c8 aeee576 4a355c8 aeee576 4a355c8 aeee576 4a355c8 aeee576 4a355c8 aeee576 4a355c8 aeee576 4a355c8 aeee576 4a355c8 aeee576 4a355c8 aeee576 4a355c8 aeee576 4a355c8 aeee576 4a355c8 aeee576 4a355c8 aeee576 4a355c8 338ce2e aeee576 4a355c8 aeee576 4a355c8 338ce2e aeee576 9594d6e aeee576 159d2da 338ce2e e5e7739 338ce2e e5e7739 338ce2e e5e7739 4a355c8 e5e7739 4a355c8 e5e7739 338ce2e 4a355c8 338ce2e 4a355c8 338ce2e 4a355c8 338ce2e 4a355c8 b96d40b 4a355c8 338ce2e 4a355c8 338ce2e 2303a01 338ce2e e5e7739 2303a01 159d2da 338ce2e 4a355c8 338ce2e b3dddf7 338ce2e 4a355c8 338ce2e 4a355c8 338ce2e dd65a21 338ce2e e5e7739 338ce2e e5e7739 338ce2e 11438c4 fc84218 11438c4 338ce2e 4a355c8 338ce2e 4a355c8 dd65a21 338ce2e 4a355c8 338ce2e 4a355c8 11438c4 e5e7739 338ce2e 4a355c8 aeee576 4a355c8 aeee576 e5e7739 4a355c8 159d2da 4a355c8 05875fd 4a355c8 1423d71 4a355c8 05875fd aeee576 4a355c8 aeee576 22bdbe9 338ce2e bbbff8b 4a355c8 22bdbe9 338ce2e 4a355c8 22bdbe9 159d2da a62441a | 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 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 | """HuggingFace Space for AI text detection using adaptive-classifier."""
import json
import re
import urllib.parse
import urllib.request
from datetime import datetime
from html.parser import HTMLParser
from uuid import uuid4
import gradio as gr
from PIL import Image, ImageDraw, ImageFont
from adaptive_classifier import AdaptiveClassifier
# ---------------------------------------------------------------------------
# Model
# ---------------------------------------------------------------------------
print("Loading model...")
classifier = AdaptiveClassifier.from_pretrained(
"adaptive-classifier/ai-detector", use_onnx=False
)
print("Model loaded!")
# Warm-up: first inference triggers ONNX session init / JIT — do it eagerly so
# the first user-facing prediction doesn't pay that cost.
try:
classifier.predict("This is a short warm-up passage so the model session initializes before the first request.", k=2)
print("Warm-up complete.")
except Exception as e:
print(f"Warm-up skipped: {e}")
# ---------------------------------------------------------------------------
# Persistent dataset via CommitScheduler
# ---------------------------------------------------------------------------
DATASET_REPO = "adaptive-classifier/ai-detector-data"
_predictions = {} # In-memory cache
_hf_api = None
def _get_api():
global _hf_api
if _hf_api is None:
from huggingface_hub import HfApi
_hf_api = HfApi()
return _hf_api
def _load_dataset() -> list[dict]:
"""Download the full JSONL dataset from HF."""
try:
api = _get_api()
path = api.hf_hub_download(DATASET_REPO, "data/predictions.jsonl", repo_type="dataset")
records = []
for line in open(path).read().strip().split("\n"):
if line:
records.append(json.loads(line))
return records
except Exception:
return []
def _save_dataset(records: list[dict], message: str = "Update dataset"):
"""Upload the full JSONL dataset to HF."""
import io
api = _get_api()
content = "\n".join(json.dumps(r) for r in records) + "\n"
api.upload_file(
path_or_fileobj=io.BytesIO(content.encode()),
path_in_repo="data/predictions.jsonl",
repo_id=DATASET_REPO,
repo_type="dataset",
commit_message=message,
)
def save_prediction(pred_id: str, text: str, url: str, label: str, confidence: float):
"""Save a prediction to memory now, push to HF dataset in a background thread."""
record = {
"id": pred_id,
"text": text,
"url": url,
"prediction": label,
"confidence": confidence,
"feedback": None,
"timestamp": datetime.now().isoformat(),
}
_predictions[pred_id] = record
def _push():
try:
records = _load_dataset()
records.append(record)
_save_dataset(records, f"Add prediction {pred_id}")
except Exception as e:
print(f"Warning: failed to push prediction: {e}")
import threading
threading.Thread(target=_push, daemon=True).start()
def lookup_prediction(pred_id: str) -> dict | None:
"""Look up a prediction by ID — check memory, then HF dataset."""
if pred_id in _predictions:
return _predictions[pred_id]
for rec in _load_dataset():
if rec.get("id") == pred_id:
_predictions[pred_id] = rec
return rec
return None
def save_feedback(pred_id: str, feedback: str):
"""Update the existing prediction record with feedback (HF write in background)."""
if pred_id in _predictions:
_predictions[pred_id]["feedback"] = feedback
def _push():
try:
records = _load_dataset()
updated = False
for rec in records:
if rec.get("id") == pred_id:
rec["feedback"] = feedback
updated = True
break
if updated:
_save_dataset(records, f"Add feedback for {pred_id}")
except Exception as e:
print(f"Warning: failed to push feedback: {e}")
import threading
threading.Thread(target=_push, daemon=True).start()
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
SPACE_URL = "https://adaptive-classifier-ai-detector.hf.space"
HEADERS = {
"User-Agent": (
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/131.0.0.0 Safari/537.36"
),
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.9",
}
HEAD = """
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wdth,wght@12..96,75..100,300;12..96,75..100,500;12..96,75..100,800&family=JetBrains+Mono:wght@400;700&display=swap" rel="stylesheet">
"""
CSS = """
:root {
--paper: #fffaf0;
--paper-soft: #fbf2dc;
--ink: #0a0908;
--ink-soft: #2a2826;
--ink-faded: #6b6864;
--ai: #f15baa; /* fluorescent pink */
--ai-soft: #fde0ee;
--human: #1f4dd6; /* federal blue */
--human-soft: #d8e1f7;
--yellow: #ffd400;
--mint: #b8eccb;
color-scheme: light;
}
* { box-sizing: border-box; }
/* Force light mode — override Gradio's dark-mode wrappers */
html, body, .dark, .dark .gradio-container, body.dark {
color-scheme: light !important;
background: var(--paper) !important;
color: var(--ink) !important;
}
.dark .input-card,
.dark .preview-box,
.dark .preview-box textarea,
.dark .section-label,
.dark .section-label * {
background: transparent !important;
color: var(--ink) !important;
}
.dark .input-card { background: var(--paper) !important; }
.dark textarea, .dark input[type="text"] {
background: var(--paper) !important;
color: var(--ink) !important;
}
.gradio-container {
background: var(--paper) !important;
font-family: 'Bricolage Grotesque', system-ui, sans-serif !important;
font-variation-settings: 'wdth' 100, 'wght' 400, 'opsz' 14;
color: var(--ink) !important;
max-width: 860px !important;
margin: 0 auto !important;
padding: 0 !important;
position: relative;
}
/* Halftone dot field — riso print signature */
.gradio-container::before {
content: '';
position: fixed; inset: 0;
pointer-events: none; z-index: 0;
background-image:
radial-gradient(circle at center, rgba(241, 91, 170, 0.16) 1.1px, transparent 1.6px),
radial-gradient(circle at center, rgba(31, 77, 214, 0.10) 1.1px, transparent 1.6px);
background-size: 9px 9px, 13px 13px;
background-position: 0 0, 5px 5px;
}
/* Tri-color register bar across top — pink / blue / yellow */
.gradio-container::after {
content: '';
position: fixed; top: 0; left: 0; right: 0;
height: 14px;
background:
linear-gradient(90deg,
var(--ai) 0 38%,
var(--human) 38% 72%,
var(--yellow) 72% 100%);
pointer-events: none; z-index: 2;
border-bottom: 2px solid var(--ink);
}
.main, .contain {
background: transparent !important;
position: relative; z-index: 1;
padding: 0 1.6rem !important;
}
footer { display: none !important; }
/* ============ HEADER ============ */
.header-block {
padding: 3rem 0 1.2rem 0;
margin-bottom: 0.4rem;
position: relative;
}
.wordmark {
font-family: 'Bricolage Grotesque', sans-serif !important;
font-variation-settings: 'wdth' 88, 'wght' 800, 'opsz' 96;
font-size: 4.4rem;
font-weight: 800;
letter-spacing: -0.06em;
line-height: 0.9;
color: var(--ink);
text-decoration: none !important;
display: inline-block;
margin: 0;
}
.wordmark .slash {
color: var(--ai);
font-weight: 800;
padding: 0;
display: inline-block;
transform: translateY(-0.04em);
}
a.wordmark { transition: transform 0.2s ease; }
a.wordmark:hover { transform: rotate(-1deg); }
.subline {
font-family: 'Bricolage Grotesque', sans-serif;
font-variation-settings: 'wdth' 100, 'wght' 400, 'opsz' 14;
font-size: 1.05rem;
color: var(--ink-soft);
line-height: 1.5;
margin: 1.1rem 0 0 0;
max-width: 540px;
}
.subline em {
font-style: italic;
font-weight: 700;
color: var(--ink);
background: linear-gradient(transparent 62%, var(--yellow) 62%);
padding: 0 0.1rem;
}
/* ============ TABS ============ */
.tabs { background: transparent !important; border: none !important; }
.tab-nav {
background: transparent !important;
border: none !important;
border-bottom: 2px solid var(--ink) !important;
border-radius: 0 !important;
padding: 0 !important;
margin-top: 1.6rem !important;
gap: 0 !important;
}
.tab-nav button {
font-family: 'JetBrains Mono', monospace !important;
font-size: 0.78rem !important; font-weight: 700 !important;
letter-spacing: 0.22em !important; text-transform: uppercase !important;
color: var(--ink) !important;
background: var(--paper) !important;
border: 2px solid var(--ink) !important;
border-bottom: 2px solid var(--ink) !important;
border-radius: 0 !important;
padding: 0.7rem 0 !important;
margin: 0 0.5rem -2px 0 !important;
transition: background 0.12s ease, color 0.12s ease !important;
position: relative;
min-width: 120px !important;
text-align: center !important;
box-sizing: border-box !important;
}
.tab-nav button:hover {
background: var(--yellow) !important;
}
.tab-nav button.selected {
color: var(--paper) !important;
background: var(--ink) !important;
border: 2px solid var(--ink) !important;
border-bottom: 2px solid var(--ink) !important;
}
.tab-nav button.selected::after {
content: '';
position: absolute;
left: 0; right: 0; bottom: -8px;
height: 4px;
background: var(--ai);
}
.tabitem {
background: transparent !important; border: none !important;
padding: 1.4rem 0 !important; min-height: 540px !important;
}
/* ============ SECTION LABEL ============ */
.section-label {
font-family: 'JetBrains Mono', monospace !important;
font-size: 0.62rem !important; font-weight: 700 !important;
color: var(--ink) !important;
background: transparent !important;
letter-spacing: 0.24em !important; text-transform: uppercase !important;
margin: 0 0 0.6rem 0 !important; padding: 0 !important;
display: flex !important; align-items: baseline !important; gap: 0.6rem !important;
}
.section-label .tag {
font-family: 'Bricolage Grotesque', sans-serif !important;
color: var(--ink-faded) !important;
background: transparent !important;
font-weight: 400 !important; letter-spacing: 0 !important;
text-transform: none !important;
font-size: 0.78rem !important;
}
/* ============ CARDS — bold-bordered riso zine blocks ============ */
.input-card {
background: var(--paper) !important;
border: 2px solid var(--ink) !important;
border-radius: 0 !important;
padding: 1.2rem 1.3rem !important;
margin: 0 0 1.4rem 0 !important;
position: relative !important;
box-shadow: 5px 5px 0 var(--ink) !important;
}
/* ============ INPUT HINT — live char-counter ============ */
.input-hint {
margin: 0.4rem 0 0 0 !important;
padding: 0 !important;
background: transparent !important;
border: none !important;
font-family: 'JetBrains Mono', monospace !important;
font-size: 0.7rem !important;
color: var(--ink-faded) !important;
letter-spacing: 0.04em !important;
}
.input-hint strong { color: var(--ink); font-weight: 700; }
.input-hint .hint-meta { color: var(--ink); font-weight: 700; }
.input-hint .hint-warn {
color: var(--ink);
background: var(--yellow);
padding: 0 0.4rem;
font-weight: 700;
border: 1px solid var(--ink);
}
/* ============ STATUS / ERROR MESSAGE ============ */
.status-msg {
margin: 0.4rem 0 1rem 0 !important;
padding: 0 !important;
background: transparent !important;
border: none !important;
}
.status-msg .status-inner {
background: var(--yellow);
border: 2px solid var(--ink);
box-shadow: 4px 4px 0 var(--ink);
padding: 0.9rem 1.1rem;
font-family: 'Bricolage Grotesque', sans-serif;
font-size: 0.95rem;
font-weight: 500;
color: var(--ink);
}
/* ============ FORM CONTROLS ============ */
textarea, input[type="text"] {
font-family: 'Bricolage Grotesque', system-ui, sans-serif !important;
font-variation-settings: 'wdth' 100, 'wght' 400, 'opsz' 14;
font-size: 1rem !important; line-height: 1.55 !important;
color: var(--ink) !important;
background: var(--paper) !important;
border: 1.5px solid var(--ink) !important;
border-radius: 0 !important;
padding: 0.75rem 0.85rem !important;
transition: all 0.12s ease !important;
caret-color: var(--ai) !important;
box-shadow: none !important;
}
textarea::placeholder, input[type="text"]::placeholder {
color: var(--ink-faded) !important;
}
textarea:focus, input[type="text"]:focus {
border-color: var(--ai) !important;
box-shadow: 3px 3px 0 var(--ai) !important;
outline: none !important;
}
label span {
font-family: 'JetBrains Mono', monospace !important;
font-size: 0.58rem !important; font-weight: 700 !important;
text-transform: uppercase !important; letter-spacing: 0.28em !important;
color: var(--ink-faded) !important;
}
/* ============ PRIMARY BUTTON — pink stamp ============ */
.detect-btn {
font-family: 'JetBrains Mono', monospace !important;
font-size: 0.72rem !important; font-weight: 700 !important;
letter-spacing: 0.22em !important; text-transform: uppercase !important;
background: var(--ink) !important;
color: var(--paper) !important;
border: 2px solid var(--ink) !important;
border-radius: 0 !important;
padding: 0.9rem 1.8rem !important;
cursor: pointer !important;
transition: all 0.12s ease !important;
box-shadow: 4px 4px 0 var(--ai) !important;
margin-top: 0.8rem !important;
}
.detect-btn:hover {
background: var(--ai) !important;
color: var(--ink) !important;
box-shadow: 4px 4px 0 var(--human) !important;
transform: translate(-2px, -2px) !important;
}
.detect-btn:active {
transform: translate(2px, 2px) !important;
box-shadow: 0 0 0 var(--ai) !important;
}
/* ============ ACTION ROWS (feedback + share) ============ */
.action-row {
margin: 0.7rem 0 0 0 !important;
gap: 0.5rem !important;
display: flex !important;
flex-direction: row !important;
flex-wrap: wrap !important;
justify-content: flex-start !important;
align-items: center !important;
background: transparent !important;
border: none !important;
}
/* Share-card image is the result display */
#share-card {
margin: 0.3rem 0 0.6rem 0 !important;
padding: 0 !important;
background: transparent !important;
border: none !important;
}
#share-card .image-frame,
#share-card .image-container,
#share-card .gradio-image {
background: transparent !important;
border: none !important;
padding: 0 !important;
border-radius: 0 !important;
}
#share-card img {
display: block !important;
max-width: 100% !important;
width: 100% !important;
height: auto !important;
border: 2px solid var(--ink) !important;
border-radius: 0 !important;
box-shadow: 5px 5px 0 var(--ink);
}
/* ============ CHIP BUTTONS — natural width, stamp shadow ============ */
.chip-btn {
font-family: 'JetBrains Mono', monospace !important;
font-size: 0.64rem !important; font-weight: 700 !important;
letter-spacing: 0.18em !important; text-transform: uppercase !important;
background: var(--paper) !important;
color: var(--ink) !important;
border: 1.5px solid var(--ink) !important;
border-radius: 0 !important;
padding: 0.55rem 1rem !important;
margin: 0 !important;
cursor: pointer !important;
transition: background 0.12s ease, transform 0.12s ease, box-shadow 0.12s ease !important;
box-shadow: 2px 2px 0 var(--ink) !important;
flex: 0 0 auto !important;
width: auto !important;
min-width: 0 !important;
max-width: none !important;
white-space: nowrap !important;
line-height: 1 !important;
}
.chip-btn:hover { transform: translate(-1px, -1px) !important; box-shadow: 3px 3px 0 var(--ink) !important; }
.chip-btn:active { transform: translate(1px, 1px) !important; box-shadow: 1px 1px 0 var(--ink) !important; }
.chip-btn.ok:hover { background: var(--mint) !important; }
.chip-btn.no:hover { background: var(--ai-soft) !important; }
.chip-btn.share:hover { background: var(--yellow) !important; }
.feedback-msg {
font-family: 'JetBrains Mono', monospace !important;
font-size: 0.68rem !important; font-weight: 700 !important;
color: var(--ink) !important;
background: var(--mint);
border: 1.5px solid var(--ink);
padding: 0.55rem 0.9rem !important;
letter-spacing: 0.16em !important;
text-transform: uppercase;
display: inline-block;
margin-top: 0.6rem;
}
.feedback-msg::before { content: '✓ '; color: var(--human); font-weight: 700; }
/* ============ EXAMPLES & PREVIEW ============ */
.examples-heading {
font-family: 'JetBrains Mono', monospace !important;
font-size: 0.6rem !important; font-weight: 700 !important;
letter-spacing: 0.3em !important; text-transform: uppercase !important;
color: var(--ink) !important;
margin: 1.6rem 0 0.6rem 0 !important;
display: flex; align-items: center; gap: 0.6rem;
}
.examples-heading::before {
content: '';
display: inline-block;
width: 12px; height: 12px;
background: var(--human);
border: 1.5px solid var(--ink);
}
.gallery { gap: 0.6rem !important; flex-wrap: wrap !important; }
.gallery .gallery-item,
.gallery > div > div {
background: var(--paper) !important;
border: 1.5px solid var(--ink) !important;
border-radius: 0 !important;
padding: 0.7rem 0.9rem !important;
transition: all 0.12s ease !important;
cursor: pointer !important;
color: var(--ink) !important;
font-family: 'Bricolage Grotesque', sans-serif !important;
font-size: 0.88rem !important;
line-height: 1.45 !important;
box-shadow: 3px 3px 0 var(--ink) !important;
}
.gallery .gallery-item:hover,
.gallery > div > div:hover {
background: var(--yellow) !important;
transform: translate(-2px, -2px);
box-shadow: 5px 5px 0 var(--ink) !important;
}
.gallery .gallery-item *,
.gallery .gallery-item textarea,
.gallery .gallery-item span,
.gallery .gallery-item div {
color: var(--ink) !important;
background: transparent !important;
font-family: 'Bricolage Grotesque', sans-serif !important;
font-size: 0.88rem !important;
border: none !important;
}
.preview-box textarea {
color: var(--ink-soft) !important;
font-size: 0.95rem !important;
font-family: 'Bricolage Grotesque', sans-serif !important;
background: var(--paper-soft) !important;
border: 1.5px solid var(--ink) !important;
}
.gr-group, .gr-block, .gr-box, .gr-panel {
background: transparent !important; border: none !important;
}
.gr-padded { padding: 0 !important; }
/* ============ FOOTER ============ */
.info-strip {
border-top: 1.5px solid var(--ink);
margin-top: 2.4rem;
padding: 1rem 0 2.5rem 0;
text-align: left;
}
.info-strip p.links {
font-family: 'JetBrains Mono', monospace !important;
font-size: 0.68rem !important; font-weight: 700 !important;
color: var(--ink) !important;
letter-spacing: 0.18em !important; text-transform: uppercase !important;
margin: 0 0 0.5rem 0 !important; line-height: 1.6;
}
.info-strip .note {
font-weight: 400 !important;
color: var(--ink-faded) !important;
text-transform: none !important;
letter-spacing: 0.06em !important;
font-style: italic;
margin-left: 0.1rem;
}
.info-strip a {
color: var(--ink) !important;
text-decoration: none !important;
border-bottom: 1.5px solid var(--ink);
padding: 0 1px 1px 1px;
transition: color 0.12s ease, border-color 0.12s ease;
background: none;
}
.info-strip a:hover {
color: var(--ai) !important;
border-bottom-color: var(--ai);
}
.info-strip .sep {
color: var(--ink-faded);
margin: 0 0.55rem;
background: none; border: none; padding: 0;
display: inline;
font-weight: 400;
}
/* hide share-card image toolbars */
#share-card .image-toolbar, #text-share-card .image-toolbar,
#share-card .icon-buttons, #text-share-card .icon-buttons,
#share-card button[aria-label], #text-share-card button[aria-label] { display: none !important; }
"""
HUMAN_EXAMPLE = (
"Nottinghamshire Healthcare NHS Trust is proposing to close Broomhill House "
"in Gedling and another unit at Heather Close in Mansfield. The trust said "
"patient feedback showed most preferred to be cared for in their own homes "
"rather than a hospital setting. Staff and patients at both sites have been "
"informed of the consultation. The proposals would see 38 inpatient beds "
"replaced by more intensive community support. Mark Stocks, the trust medical "
"director, said the community-based approach meant more patients could be "
"helped. He said a full public consultation would take place before any "
"final decisions were made."
)
AI_EXAMPLE = (
"Understanding Intramuscular Injections: A Vital Medical Delivery Method. "
"When we think about receiving medication, most people immediately picture "
"swallowing pills or receiving shots in the arm. That said, intramuscular "
"injections represent a crucial and nuanced approach to drug delivery that "
"deserves a closer look. These injections deliver medication directly into "
"muscle tissue, allowing for efficient absorption into the bloodstream. "
"The technique requires careful consideration of injection site selection, "
"needle gauge, and proper anatomical knowledge to ensure both safety and "
"efficacy for the patient."
)
# ---------------------------------------------------------------------------
# HTML extraction
# ---------------------------------------------------------------------------
class _TextExtractor(HTMLParser):
def __init__(self):
super().__init__()
self._parts, self._skip = [], False
self._skip_tags = {"script", "style", "nav", "header", "footer", "noscript"}
def handle_starttag(self, tag, attrs):
if tag in self._skip_tags:
self._skip = True
if tag in ("p", "br", "div", "h1", "h2", "h3", "h4", "li", "tr"):
self._parts.append("\n")
def handle_endtag(self, tag):
if tag in self._skip_tags:
self._skip = False
def handle_data(self, data):
if not self._skip:
self._parts.append(data)
def get_text(self):
return re.sub(r"\s+", " ", " ".join(self._parts)).strip()
try:
import trafilatura
_HAVE_TRAFILATURA = True
except ImportError:
_HAVE_TRAFILATURA = False
def fetch_url(url: str) -> str:
if not url or not url.strip():
return ""
url = url.strip()
if not url.startswith(("http://", "https://")):
url = "https://" + url
req = urllib.request.Request(url, headers=HEADERS)
with urllib.request.urlopen(req, timeout=15) as resp:
html = resp.read().decode("utf-8", errors="ignore")
# Prefer trafilatura — it extracts just the main article body,
# dropping nav menus, sidebars, footers, infoboxes, edit links, ToCs, references.
if _HAVE_TRAFILATURA:
extracted = trafilatura.extract(
html, url=url,
include_comments=False,
include_tables=False,
include_links=False,
deduplicate=True,
favor_recall=False,
)
if extracted and len(extracted.split()) >= 50:
return extracted
# Fallback: simple home-grown HTML stripper.
parser = _TextExtractor()
parser.feed(html)
return parser.get_text()
# ---------------------------------------------------------------------------
# Result card image
# ---------------------------------------------------------------------------
def make_result_card(source: str, label: str, confidence: float, extracted_text: str = "") -> Image.Image:
"""Share card layout (top-down):
1. Tri-color register strip
2. Header strip: wordmark left, TRY IT -> URL top-right
3. Verdict block (in one paper sheet):
- VERDICT label
- Small verdict word + percentage
- Hatched confidence bar
- TEXT/URL ANALYZED label
- 3 lines of source preview
"""
W, H = 1100, 560
PAPER = "#fffaf0"
PAPER_SOFT = "#fbf2dc"
INK = "#0a0908"
INK_F = "#6b6864"
AI = "#f15baa"
HUMAN = "#1f4dd6"
YELLOW = "#ffd400"
is_ai = label.lower() == "ai"
accent = AI if is_ai else HUMAN
verdict_word = "ai" if is_ai else "human"
img = Image.new("RGB", (W, H), PAPER)
draw = ImageDraw.Draw(img)
def load(*paths_sizes):
for path, size in paths_sizes:
try:
return ImageFont.truetype(path, size)
except OSError:
continue
return ImageFont.load_default()
# Smaller verdict (was 160)
f_verdict = load(
("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 112),
("/System/Library/Fonts/Supplemental/Arial Bold.ttf", 112),
)
f_wordmark = load(
("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 26),
("/System/Library/Fonts/Supplemental/Arial Bold.ttf", 26),
)
f_try = load(
("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 14),
("/System/Library/Fonts/Supplemental/Arial Bold.ttf", 14),
)
f_url = load(
("/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf", 14),
("/System/Library/Fonts/Menlo.ttc", 14),
)
f_pct = load(
("/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf", 44),
("/System/Library/Fonts/Menlo.ttc", 44),
)
f_pct_mark = load(
("/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf", 24),
("/System/Library/Fonts/Menlo.ttc", 24),
)
f_mono_s = load(
("/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf", 13),
("/System/Library/Fonts/Menlo.ttc", 13),
)
f_preview = load(
("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 17),
("/System/Library/Fonts/Supplemental/Arial.ttf", 17),
)
f_url_preview = load(
("/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf", 15),
("/System/Library/Fonts/Menlo.ttc", 15),
)
# ===== Tri-color strip =====
bar_h = 8
third = W // 3
draw.rectangle([0, 0, third, bar_h], fill=AI)
draw.rectangle([third, 0, third * 2, bar_h], fill=HUMAN)
draw.rectangle([third * 2, 0, W, bar_h], fill=YELLOW)
# ===== Header strip =====
strip_top = bar_h
strip_h = 90
draw.line([(0, strip_top + strip_h), (W, strip_top + strip_h)], fill=INK, width=1)
# Wordmark left
wm_x, wm_y = 40, strip_top + 22
draw.text((wm_x, wm_y), "ai", fill=INK, font=f_wordmark)
bbox = draw.textbbox((wm_x, wm_y), "ai", font=f_wordmark)
draw.text((bbox[2] + 2, wm_y), "/", fill=AI, font=f_wordmark)
bbox2 = draw.textbbox((bbox[2] + 2, wm_y), "/", font=f_wordmark)
draw.text((bbox2[2] + 2, wm_y), "detector", fill=INK, font=f_wordmark)
draw.text((wm_x, wm_y + 36), "HUMAN-vs-AI TEXT CLASSIFIER", fill=INK_F, font=f_mono_s)
# TRY IT -> URL top-right
full_url = "adaptive-classifier-ai-detector.hf.space"
url_bbox = draw.textbbox((0, 0), full_url, font=f_url)
url_w = url_bbox[2] - url_bbox[0]
try_bbox = draw.textbbox((0, 0), "TRY IT →", font=f_try)
try_w = try_bbox[2] - try_bbox[0]
line_w = max(url_w, try_w)
right_edge = W - 40
line1_x = right_edge - try_w
line2_x = right_edge - url_w
draw.text((line1_x, strip_top + 22), "TRY IT →", fill=INK, font=f_try)
draw.text((line2_x, strip_top + 42), full_url, fill=INK, font=f_url)
# Underline the URL so it reads as clickable
draw.line([(line2_x, strip_top + 60), (line2_x + url_w, strip_top + 60)], fill=accent, width=2)
# ===== Verdict block =====
bx, by = 40, strip_top + strip_h + 26
bw = W - 80
bh = H - by - 30
# offset shadow
draw.rectangle([bx + 7, by + 7, bx + bw + 7, by + bh + 7], fill=accent)
# main block
draw.rectangle([bx, by, bx + bw, by + bh], fill=PAPER, outline=INK, width=2)
pad_x = 36
inner_x = bx + pad_x
inner_right = bx + bw - pad_x
# VERDICT label
cur_y = by + 26
draw.text((inner_x, cur_y), "VERDICT", fill=INK_F, font=f_mono_s)
cur_y += 22
# Verdict word + colored period + percentage on the right
word_y = cur_y
draw.text((inner_x, word_y), verdict_word, fill=INK, font=f_verdict)
wbb = draw.textbbox((inner_x, word_y), verdict_word, font=f_verdict)
draw.text((wbb[2] + 4, word_y), ".", fill=accent, font=f_verdict)
# Percentage on the right, vertically centered with verdict word
pct = int(round(confidence * 100))
pct_str = str(pct)
pct_bbox = draw.textbbox((0, 0), pct_str, font=f_pct)
pct_w = pct_bbox[2] - pct_bbox[0]
mark_bbox = draw.textbbox((0, 0), "%", font=f_pct_mark)
mark_w = mark_bbox[2] - mark_bbox[0]
pct_total_w = pct_w + 6 + mark_w
pct_x = inner_right - pct_total_w
pct_y = word_y + 30
draw.text((pct_x, pct_y), pct_str, fill=INK, font=f_pct)
draw.text((pct_x + pct_w + 6, pct_y + 16), "%", fill=INK_F, font=f_pct_mark)
cur_y = word_y + 120
# Hatched confidence bar
bar_y = cur_y
bar_h_px = 20
bar_w = bw - 2 * pad_x
draw.rectangle([inner_x, bar_y, inner_x + bar_w, bar_y + bar_h_px], fill=PAPER_SOFT, outline=INK, width=2)
fw = int(bar_w * confidence)
if fw > 4:
draw.rectangle([inner_x + 2, bar_y + 2, inner_x + fw - 2, bar_y + bar_h_px - 2], fill=accent)
for x in range(inner_x - bar_h_px, inner_x + fw, 6):
draw.line([(x, bar_y + bar_h_px - 2), (x + bar_h_px - 2, bar_y + 2)], fill=PAPER, width=1)
cur_y = bar_y + bar_h_px + 26
# Source preview — under verdict
is_url_src = source.startswith("http") or source.startswith("www")
src_label = "URL ANALYZED" if is_url_src else "TEXT ANALYZED"
draw.text((inner_x, cur_y), src_label, fill=INK_F, font=f_mono_s)
cur_y += 22
max_w = bw - 2 * pad_x
# URL case: show URL on one mono line, then 3 lines of extracted text below.
# Text case: show 4 lines of the input text.
if is_url_src:
url_line = source.strip()
while f_url_preview.getlength(url_line) > max_w and len(url_line) > 10:
url_line = url_line[:-4] + "..."
draw.text((inner_x, cur_y), url_line, fill=INK, font=f_url_preview)
cur_y += 24
body = (extracted_text or "").strip().replace("\n", " ")
pf = f_preview
max_lines = 3
else:
body = source.strip().replace("\n", " ")
pf = f_preview
max_lines = 4
lines, current = [], ""
for w in body.split():
test = (current + " " + w).strip()
if pf.getlength(test) > max_w:
if current:
lines.append(current)
current = w
else:
current = test
if len(lines) >= max_lines:
break
if current and len(lines) < max_lines:
lines.append(current)
if lines:
total_in_lines = sum(len(l) for l in lines) + len(lines) - 1
if len(body) > total_in_lines + 5:
last = lines[-1]
while pf.getlength(last + "...") > max_w and len(last) > 4:
last = last[:-1]
lines[-1] = last + "..."
line_h = 24
for i, line in enumerate(lines):
draw.text((inner_x, cur_y + i * line_h), line, fill=INK, font=pf)
return img
def _error_label(msg: str) -> dict:
return {msg: 1.0}
def _classify(text: str) -> dict:
if not text or len(text.strip().split()) < 10:
return _error_label("Please enter at least a few sentences (~50 words)")
predictions = classifier.predict(text, k=2)
return {label: round(score, 4) for label, score in predictions}
def detect_text_full(text: str):
"""Returns (result, share_link, card, pred_id)"""
# Mirror the URL flow: cap at 2,000 chars (~512 tokens) before scoring.
scored_text = text.strip()[:2000]
result = _classify(scored_text)
if any(k.startswith("Please") for k in result):
return result, "", None, ""
top_label = max(result, key=result.get)
pred_id = uuid4().hex[:12]
save_prediction(pred_id, scored_text, "", top_label, result[top_label])
share_link = f"{SPACE_URL}/?id={pred_id}"
card = make_result_card(scored_text, top_label, result[top_label])
return result, share_link, card, pred_id
def detect_url_full(url: str):
"""Returns (result, preview_text, share_link, card, pred_id)"""
if not url or not url.strip():
return _error_label("Please enter a URL"), "", "", None, ""
try:
text = fetch_url(url)
except Exception as e:
return _error_label(f"Could not fetch URL: {e}"), "", "", None, ""
js_hints = ["javascript is not available", "enable javascript", "javascript is disabled",
"please enable js", "requires javascript", "noscript",
"if you are not redirected", "please click here"]
text_lower = text.lower()
if any(h in text_lower for h in js_hints):
return _error_label("This site requires JavaScript (e.g. Twitter/X). Paste the text directly instead."), "", "", None, ""
if len(text.split()) < 10:
return _error_label("Not enough readable text found at that URL"), text[:500], "", None, ""
# full_text: everything trafilatura extracted (shown to user for assurance).
# scored_text: first ~2000 chars (~512 tokens, RoBERTa limit) — what the model sees.
full_text = text
scored_text = text[:2000]
result = _classify(scored_text)
if any(k.startswith("Please") or k.startswith("Not enough") for k in result):
return result, full_text[:500], "", None, ""
top_label = max(result, key=result.get)
pred_id = uuid4().hex[:12]
save_prediction(pred_id, scored_text, url.strip(), top_label, result[top_label])
share_link = f"{SPACE_URL}/?id={pred_id}"
card = make_result_card(url.strip(), top_label, result[top_label], extracted_text=scored_text)
return result, full_text, share_link, card, pred_id
# ---------------------------------------------------------------------------
# UI
# ---------------------------------------------------------------------------
URL_PATTERN = re.compile(r"^(https?://|www\.)\S+", re.IGNORECASE)
def _is_url(s: str) -> bool:
s = s.strip()
if URL_PATTERN.match(s):
return True
# Bare domain like "example.com/path"
if " " not in s and len(s) < 250 and re.match(r"^[a-zA-Z0-9.-]+\.[a-z]{2,}(/.*)?$", s):
return True
return False
def detect_any(input_text: str):
"""Return (result_dict, preview_text, share_link, card, pred_id, was_url)."""
s = (input_text or "").strip()
if not s:
return _error_label("Please enter text or a URL"), "", "", None, "", False
if _is_url(s):
result, preview, link, card, pid = detect_url_full(s)
return result, preview, link, card, pid, True
result, link, card, pid = detect_text_full(s)
return result, "", link, card, pid, False
def _render_verdict(result: dict) -> str:
"""Render the verdict block as HTML — single confidence row for the top class."""
if not result:
return ""
if any(k.startswith(("Please", "Not enough", "Could not", "This site"))
for k in result):
msg = next(iter(result))
return (
'<div class="verdict-block error">'
f' <div class="verdict-error">{msg}</div>'
'</div>'
)
top = max(result, key=result.get)
top_conf = result[top]
accent_class = "ai" if top == "ai" else "human"
pct = int(round(top_conf * 100))
return f'''
<div class="verdict-block {accent_class}">
<div class="verdict-meta">VERDICT</div>
<div class="verdict-word">{top}<span class="verdict-dot">.</span></div>
<div class="verdict-row">
<div class="vrow-bar"><div class="vrow-fill" style="width: {top_conf*100:.1f}%;"></div></div>
<span class="vrow-pct">{pct}<span class="vrow-pct-mark">%</span></span>
</div>
</div>
'''
with gr.Blocks(css=CSS, head=HEAD, title="AI Detector", theme=gr.themes.Base()) as demo:
gr.HTML("""
<div class="header-block">
<a class="wordmark" href="https://huggingface.co/adaptive-classifier/ai-detector" target="_blank">ai<span class="slash">/</span>detector</a>
<div class="subline">
A small classifier that reads a passage of text, or a web page at a URL,
and tells you whether it was written by a <em>human</em> or by a <em>language model</em>.
</div>
</div>
""")
with gr.Group(elem_classes="input-card"):
main_input = gr.Textbox(
lines=6,
placeholder="paste text or a URL here…",
label="Input",
show_label=False,
)
input_hint = gr.HTML(visible=False, elem_classes="input-hint")
main_btn = gr.Button("Analyze", variant="primary", elem_classes="detect-btn")
status_msg = gr.HTML(visible=False, elem_classes="status-msg")
# The share card IS the result display — no separate verdict block.
share_card = gr.Image(visible=False, type="pil", elem_id="share-card", show_label=False, container=False)
main_pred_id = gr.Textbox(visible=False, elem_id="main-pred-id")
share_link = gr.Textbox(visible=False, interactive=False, elem_id="share-url", show_label=False, container=False)
# Single action row: feedback (correct / incorrect) + share (link / image / download)
with gr.Row(visible=False, elem_classes="action-row") as actions_row:
fb_up = gr.Button("Correct", elem_classes="chip-btn ok")
fb_down = gr.Button("Incorrect", elem_classes="chip-btn no")
copy_link_btn = gr.Button("Copy link", elem_classes="chip-btn share")
copy_img_btn = gr.Button("Copy image", elem_classes="chip-btn share")
dl_img_btn = gr.Button("Download image", elem_classes="chip-btn share")
fb_msg = gr.HTML(visible=False, elem_classes="feedback-msg")
with gr.Group(elem_classes="input-card", visible=False) as preview_group:
gr.HTML('<div class="section-label">Extracted from URL<span class="tag">full text shown · first 2,000 characters sent to the model</span></div>')
url_preview = gr.Textbox(label="", lines=5, interactive=False, elem_classes="preview-box", show_label=False)
def run_and_show(input_text):
result, preview, link, card, pid, is_url = detect_any(input_text)
has_card = card is not None
is_error = (not has_card) and result and any(
k.startswith(("Please", "Not enough", "Could not", "This site"))
for k in result
)
error_html = ""
if is_error:
msg = next(iter(result))
error_html = f'<div class="status-inner">⚠ {msg}</div>'
return (
gr.update(value=error_html, visible=is_error),
gr.update(value=card, visible=has_card),
gr.update(value=pid, visible=False),
gr.update(value=link, visible=has_card),
gr.update(visible=has_card),
gr.update(visible=False),
gr.update(visible=is_url and has_card),
preview,
)
main_btn.click(
fn=run_and_show, inputs=main_input,
outputs=[status_msg, share_card, main_pred_id, share_link, actions_row, fb_msg, preview_group, url_preview],
api_name="detect",
)
def _update_hint(text):
s = (text or "").strip()
n = len(s)
if n == 0:
return gr.update(value="", visible=False)
# Treat URL inputs separately — no truncation warning, just say it'll be fetched.
if _is_url(s):
return gr.update(value=f'<span class="hint-meta">URL detected</span> · will fetch and analyze the page', visible=True)
if n > 2000:
extra = n - 2000
return gr.update(
value=f'<span class="hint-warn">{n:,} chars</span> · first <strong>2,000</strong> sent to the model ({extra:,} chars truncated)',
visible=True,
)
return gr.update(value=f'<span class="hint-meta">{n:,} chars</span> · under the 2,000-char model limit', visible=True)
main_input.change(fn=_update_hint, inputs=main_input, outputs=input_hint, show_progress="hidden")
def fb_positive(pid):
if pid:
save_feedback(pid, "correct")
return gr.update(value='Thanks for your feedback!', visible=True)
def fb_negative(pid):
if pid:
save_feedback(pid, "incorrect")
return gr.update(value='Thanks for your feedback!', visible=True)
fb_up.click(fn=fb_positive, inputs=main_pred_id, outputs=[fb_msg])
fb_down.click(fn=fb_negative, inputs=main_pred_id, outputs=[fb_msg])
copy_link_btn.click(fn=None, inputs=share_link, js="(u) => { navigator.clipboard.writeText(u); }")
copy_img_btn.click(fn=None, js="""() => {
const img = document.querySelector('#share-card img');
if (img) { const c = document.createElement('canvas'); c.width = img.naturalWidth; c.height = img.naturalHeight;
c.getContext('2d').drawImage(img, 0, 0);
c.toBlob(b => navigator.clipboard.write([new ClipboardItem({'image/png': b})]), 'image/png'); }
}""")
dl_img_btn.click(fn=None, js="""() => {
const img = document.querySelector('#share-card img');
if (img) { const a = document.createElement('a'); a.href = img.src; a.download = 'ai-detector-result.png'; a.click(); }
}""")
gr.HTML('<div class="examples-heading">Try one</div>')
gr.Examples(
examples=[
[HUMAN_EXAMPLE],
[AI_EXAMPLE],
["http://www.paulgraham.com/makersschedule.html"],
["https://garryslist.org/posts/richmond-just-voted-to-reinstate-their-flock-cameras-after-crime-spiked"],
],
inputs=main_input, label="",
)
gr.HTML("""
<div class="info-strip">
<p class="links">
<a href="https://huggingface.co/adaptive-classifier/ai-detector">Model</a>
<span class="sep">·</span>
<a href="https://huggingface.co/datasets/adaptive-classifier/ai-detector-data">Dataset</a>
<span class="sep">·</span>
<a href="https://github.com/codelion/adaptive-classifier">Source code</a>
<span class="sep">·</span>
<span class="note">best with 50+ words</span>
</p>
</div>
""")
def _on_load(request: gr.Request):
pred_id = request.query_params.get("id", "")
rec = lookup_prediction(pred_id) if pred_id else None
if not rec:
hide = gr.update(visible=False)
return ("", gr.update(value="", visible=False), gr.update(value=None, visible=False),
gr.update(value="", visible=False), gr.update(value="", visible=False), hide, hide, hide, "")
is_url = bool(rec.get("url"))
if is_url:
card = make_result_card(rec["url"], rec["prediction"], rec["confidence"], extracted_text=rec["text"])
else:
card = make_result_card(rec["text"], rec["prediction"], rec["confidence"])
link = f"{SPACE_URL}/?id={pred_id}"
main_value = rec["url"] if is_url else rec["text"]
return (
main_value,
gr.update(value="", visible=False),
gr.update(value=card, visible=True),
gr.update(value=pred_id, visible=False),
gr.update(value=link, visible=True),
gr.update(visible=True),
gr.update(visible=False),
gr.update(visible=is_url),
rec["text"] if is_url else "",
)
demo.load(
fn=_on_load, inputs=None,
outputs=[main_input, status_msg, share_card, main_pred_id, share_link, actions_row, fb_msg, preview_group, url_preview],
)
if __name__ == "__main__":
demo.launch(share=False, ssr_mode=False)
|