Spaces:
Sleeping
Sleeping
File size: 49,777 Bytes
4dc7a21 54d2747 4dc7a21 54d2747 3f1e54e 3f6cbe6 54d2747 3b1ecaa 3f6cbe6 65ff6c9 2e1637f 3f6cbe6 611dc13 3f6cbe6 54d2747 3f6cbe6 54d2747 3b1ecaa 54d2747 921dd02 6f78dda 54d2747 6f78dda ea3c064 3b1ecaa ea3c064 6f78dda ea3c064 6f78dda ea3c064 6f78dda 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa ea3c064 3b1ecaa 54d2747 6f78dda 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 6f78dda 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3f6cbe6 3b1ecaa 54d2747 3b1ecaa 54d2747 6f78dda 3f6cbe6 3b1ecaa 54d2747 3b1ecaa 54d2747 6f78dda 3f6cbe6 3b1ecaa 54d2747 3b1ecaa 54d2747 6f78dda 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 3f6cbe6 3b1ecaa 3f6cbe6 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3f6cbe6 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 3f6cbe6 54d2747 3f6cbe6 54d2747 3f6cbe6 54d2747 3f6cbe6 54d2747 3f6cbe6 54d2747 3f6cbe6 54d2747 3f6cbe6 cee7af2 3b1ecaa 65ff6c9 3f6cbe6 54d2747 cee7af2 611dc13 65ff6c9 54d2747 65ff6c9 54d2747 3f6cbe6 54d2747 3f6cbe6 54d2747 3f6cbe6 54d2747 3f6cbe6 611dc13 54d2747 3f6cbe6 54d2747 3f6cbe6 fcce9fe 54d2747 3f6cbe6 54d2747 3f6cbe6 54d2747 3f6cbe6 54d2747 3f6cbe6 3f1e54e 54d2747 3f6cbe6 54d2747 611dc13 3b1ecaa 54d2747 3f6cbe6 54d2747 3f6cbe6 54d2747 3f6cbe6 611dc13 3f6cbe6 3b1ecaa 3f6cbe6 3b1ecaa 3f6cbe6 3b1ecaa 3f6cbe6 3b1ecaa 3f6cbe6 3b1ecaa 3f6cbe6 3b1ecaa 6f78dda 3b1ecaa 611dc13 3b1ecaa 611dc13 3b1ecaa 6f78dda 3b1ecaa 611dc13 3b1ecaa 6f78dda 3b1ecaa 6f78dda 3b1ecaa 3f6cbe6 4dc7a21 3b1ecaa 3f6cbe6 6f78dda 54d2747 3f6cbe6 3b1ecaa 3f6cbe6 3b1ecaa 4dc7a21 54d2747 3f6cbe6 54d2747 3f6cbe6 54d2747 3b1ecaa 3f6cbe6 54d2747 3b1ecaa 54d2747 3f6cbe6 3b1ecaa 611dc13 3b1ecaa 3f6cbe6 54d2747 3f6cbe6 54d2747 3b1ecaa 54d2747 3f6cbe6 54d2747 3f6cbe6 54d2747 3f6cbe6 4dc7a21 3f6cbe6 54d2747 3f6cbe6 54d2747 3b1ecaa 3f6cbe6 54d2747 3b1ecaa 54d2747 3f6cbe6 54d2747 3f6cbe6 3b1ecaa 54d2747 3b1ecaa 54d2747 3b1ecaa 3f6cbe6 3b1ecaa 54d2747 3b1ecaa 4dc7a21 3b1ecaa 3f6cbe6 54d2747 3f6cbe6 54d2747 3f6cbe6 54d2747 3b1ecaa 611dc13 3b1ecaa 3f6cbe6 54d2747 3f6cbe6 54d2747 3f6cbe6 54d2747 3f6cbe6 54d2747 3b1ecaa 3f6cbe6 54d2747 3f6cbe6 54d2747 3f6cbe6 54d2747 3f6cbe6 54d2747 3b1ecaa 54d2747 3f6cbe6 54d2747 3f6cbe6 54d2747 3f6cbe6 54d2747 3f6cbe6 54d2747 3f6cbe6 54d2747 3f6cbe6 54d2747 3f6cbe6 54d2747 3f6cbe6 54d2747 3f6cbe6 54d2747 3b1ecaa 611dc13 3f6cbe6 54d2747 3f6cbe6 54d2747 3f6cbe6 54d2747 3f6cbe6 3b1ecaa 3f6cbe6 a70e30f 179b962 a70e30f 611dc13 a70e30f 54d2747 | 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 | """
Dashboard β Creator-Friendly Ad Placement Recommender (Premium UI)
"""
import os
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
import streamlit as st
import json
import math
import tempfile
import pandas as pd
import plotly.graph_objects as go
import base64
from PIL import Image
from youtube_auth import get_credentials, show_login_button, logout
# ββ Page Config ββ
st.set_page_config(
page_title="Ad Placement Recommender",
page_icon="β·",
layout="wide"
)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# DESIGN SYSTEM β CSS
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap');
:root {
--bg-primary: #0a0e1a;
--bg-secondary: #0f1425;
--bg-card: rgba(22, 28, 45, 0.65);
--bg-card-solid: #161c2d;
--border-glass: rgba(99, 102, 241, 0.15);
--border-subtle: rgba(255, 255, 255, 0.06);
--accent-indigo: #6366f1;
--accent-purple: #8b5cf6;
--accent-cyan: #22d3ee;
--accent-pink: #ec4899;
--success: #10b981;
--success-glow: rgba(16, 185, 129, 0.25);
--warning: #f59e0b;
--warning-glow: rgba(245, 158, 11, 0.25);
--danger: #ef4444;
--danger-glow: rgba(239, 68, 68, 0.25);
--text-primary: #f1f5f9;
--text-secondary: #94a3b8;
--text-muted: #64748b;
--radius-sm: 8px;
--radius-md: 14px;
--radius-lg: 20px;
--radius-xl: 28px;
--glass-blur: 16px;
--transition-fast: 0.2s cubic-bezier(0.4, 0, 0.2, 1);
--transition-smooth: 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}
html, body, .stApp, [data-testid="stAppViewContainer"] {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif !important;
background: var(--bg-primary) !important;
color: var(--text-primary) !important;
}
.stApp > header { background: transparent !important; }
.main .block-container { padding-top: 2rem !important; max-width: 1200px; }
::-webkit-scrollbar { width: 6px; }
::-webkit-scrollbar-track { background: var(--bg-primary); }
::-webkit-scrollbar-thumb { background: #2d3555; border-radius: 10px; }
::-webkit-scrollbar-thumb:hover { background: #3d4570; }
@keyframes fadeInUp {
from { opacity: 0; transform: translateY(18px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes shimmer {
0% { background-position: -200% center; }
100% { background-position: 200% center; }
}
@keyframes pulseGlow {
0%, 100% { box-shadow: 0 0 20px rgba(99,102,241,0.15); }
50% { box-shadow: 0 0 35px rgba(99,102,241,0.3); }
}
@keyframes gradientShift {
0% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
100% { background-position: 0% 50%; }
}
@keyframes float {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-6px); }
}
@keyframes ringPulse {
0%, 100% { filter: drop-shadow(0 0 3px rgba(99,102,241,0.3)); }
50% { filter: drop-shadow(0 0 8px rgba(99,102,241,0.6)); }
}
@keyframes orbFloat1 {
0% { transform: translate(0, 0) scale(1); }
50% { transform: translate(5vw, 10vh) scale(1.2); }
100% { transform: translate(-5vw, 5vh) scale(0.9); }
}
@keyframes orbFloat2 {
0% { transform: translate(0, 0) scale(1); }
50% { transform: translate(-10vw, -5vh) scale(1.1); }
100% { transform: translate(5vw, -10vh) scale(1); }
}
@keyframes progressPulse {
0% { opacity: 0.6; box-shadow: 0 0 10px rgba(99,102,241,0.2); }
50% { opacity: 1; box-shadow: 0 0 25px rgba(99,102,241,0.6); }
100% { opacity: 0.6; box-shadow: 0 0 10px rgba(99,102,241,0.2); }
}
[data-testid="stAppViewContainer"] {
background-color: var(--bg-primary);
background-image:
radial-gradient(rgba(255, 255, 255, 0.03) 1px, transparent 1px),
radial-gradient(rgba(255, 255, 255, 0.03) 1px, transparent 1px);
background-position: 0 0, 20px 20px;
background-size: 40px 40px;
}
[data-testid="stAppViewContainer"]::before {
content: ''; position: fixed; top: -10%; left: -10%; width: 50vw; height: 50vw;
background: radial-gradient(circle, rgba(99,102,241,0.25) 0%, rgba(10,14,26,0) 60%);
border-radius: 50%; filter: blur(80px); z-index: 0; pointer-events: none;
animation: orbFloat1 20s infinite ease-in-out alternate;
}
[data-testid="stAppViewContainer"]::after {
content: ''; position: fixed; bottom: -10%; right: -10%; width: 60vw; height: 60vw;
background: radial-gradient(circle, rgba(34,211,238,0.2) 0%, rgba(10,14,26,0) 60%);
border-radius: 50%; filter: blur(100px); z-index: 0; pointer-events: none;
animation: orbFloat2 25s infinite ease-in-out alternate-reverse;
}
.main .block-container { z-index: 1; position: relative; }
.hero-title {
font-size: 2.6rem; font-weight: 900;
background: linear-gradient(135deg, #6366f1, #8b5cf6, #22d3ee, #6366f1);
background-size: 300% 300%;
-webkit-background-clip: text; -webkit-text-fill-color: transparent;
background-clip: text;
animation: gradientShift 6s ease infinite;
letter-spacing: -0.03em; line-height: 1.2; margin-bottom: 0.3rem;
}
.hero-subtitle {
font-size: 1.05rem; color: var(--text-secondary);
font-weight: 400; line-height: 1.6; margin-bottom: 0.5rem;
}
.hero-accent-line {
width: 60px; height: 3px; border-radius: 3px;
background: linear-gradient(90deg, var(--accent-indigo), var(--accent-cyan));
margin-bottom: 2rem;
}
.glass-card {
background: rgba(22, 28, 45, 0.5);
backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: var(--radius-lg); padding: 1.8rem;
animation: fadeInUp 0.5s ease-out both;
transition: transform var(--transition-fast), box-shadow var(--transition-fast);
}
.glass-card:hover {
transform: translateY(-4px) scale(1.01);
box-shadow: 0 15px 40px rgba(99,102,241,0.15), 0 0 20px rgba(99,102,241,0.05) inset;
border-color: rgba(99,102,241,0.3);
}
.metric-card {
background: var(--bg-card); backdrop-filter: blur(var(--glass-blur));
-webkit-backdrop-filter: blur(var(--glass-blur));
border: 1px solid var(--border-glass); border-radius: var(--radius-md);
padding: 1.4rem 1.2rem; text-align: center; position: relative; overflow: hidden;
animation: fadeInUp 0.5s ease-out both;
transition: transform var(--transition-fast), box-shadow var(--transition-fast);
}
.metric-card::before {
content: ''; position: absolute; top: 0; left: 0; right: 0; height: 3px;
background: linear-gradient(90deg, var(--accent-indigo), var(--accent-purple));
}
.metric-card:hover {
transform: translateY(-5px) scale(1.02);
box-shadow: 0 15px 45px rgba(139,92,246,0.15), 0 0 15px rgba(139,92,246,0.05) inset;
border-color: rgba(139,92,246,0.3);
}
.metric-icon {
width: 42px; height: 42px; border-radius: 12px;
display: inline-flex; align-items: center; justify-content: center;
font-size: 1.3rem; margin-bottom: 0.7rem;
}
.metric-label {
font-size: 0.78rem; font-weight: 500; color: var(--text-muted);
text-transform: uppercase; letter-spacing: 0.06em; margin-bottom: 0.4rem;
}
.metric-value { font-size: 1.9rem; font-weight: 800; letter-spacing: -0.02em; line-height: 1.1; }
.section-header {
font-size: 1.35rem; font-weight: 700; color: var(--text-primary);
margin: 2.5rem 0 0.6rem 0; display: flex; align-items: center; gap: 0.5rem;
}
.section-header::after {
content: ''; flex: 1; height: 1px;
background: linear-gradient(90deg, var(--border-glass), transparent);
margin-left: 1rem;
}
.placement-card {
background: var(--bg-card); backdrop-filter: blur(var(--glass-blur));
-webkit-backdrop-filter: blur(var(--glass-blur));
border: 1px solid rgba(16, 185, 129, 0.2); border-left: 4px solid var(--success);
border-radius: var(--radius-md); padding: 1.6rem; margin-bottom: 1rem;
animation: fadeInUp 0.5s ease-out both;
transition: transform var(--transition-fast), box-shadow var(--transition-fast);
}
.placement-card:hover {
transform: translateY(-4px) scale(1.01);
box-shadow: 0 12px 35px var(--success-glow), 0 0 15px rgba(16,185,129,0.05) inset;
border-color: rgba(16,185,129,0.4);
}
.placement-card-warn {
background: var(--bg-card); backdrop-filter: blur(var(--glass-blur));
-webkit-backdrop-filter: blur(var(--glass-blur));
border: 1px solid rgba(245, 158, 11, 0.2); border-left: 4px solid var(--warning);
border-radius: var(--radius-md); padding: 1.6rem; margin-bottom: 1rem;
animation: fadeInUp 0.5s ease-out both; transition: all var(--transition-smooth);
}
.placement-card-warn:hover {
transform: translateY(-4px) scale(1.01);
box-shadow: 0 12px 35px var(--warning-glow), 0 0 15px rgba(245,158,11,0.05) inset;
border-color: rgba(245,158,11,0.4);
}
.placement-card-bad {
background: var(--bg-card); backdrop-filter: blur(var(--glass-blur));
-webkit-backdrop-filter: blur(var(--glass-blur));
border: 1px solid rgba(239, 68, 68, 0.2); border-left: 4px solid var(--danger);
border-radius: var(--radius-md); padding: 1.6rem; margin-bottom: 1rem;
animation: fadeInUp 0.5s ease-out both; transition: all var(--transition-smooth);
}
.placement-card-bad:hover {
transform: translateY(-4px) scale(1.01);
box-shadow: 0 12px 35px var(--danger-glow), 0 0 15px rgba(239,68,68,0.05) inset;
border-color: rgba(239,68,68,0.4);
}
.placement-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem; }
.placement-title { font-size: 1.15rem; font-weight: 700; color: var(--text-primary); }
.placement-timestamp {
font-family: 'JetBrains Mono', 'Fira Code', monospace;
background: rgba(99, 102, 241, 0.15); color: var(--accent-indigo);
padding: 2px 10px; border-radius: 6px; font-size: 0.85rem; font-weight: 600;
}
.placement-body { display: flex; gap: 1.5rem; align-items: center; flex-wrap: wrap; }
.placement-stats { flex: 1; display: flex; gap: 2rem; flex-wrap: wrap; }
.stat-block .stat-label {
font-size: 0.7rem; font-weight: 600; color: var(--text-muted);
text-transform: uppercase; letter-spacing: 0.08em; margin-bottom: 0.2rem;
}
.stat-block .stat-value { font-size: 1.4rem; font-weight: 700; color: var(--text-primary); }
.stat-block .stat-value-sm { font-size: 0.95rem; font-weight: 600; color: #cbd5e1; }
.retention-ring-container {
display: flex; align-items: center; justify-content: center;
width: 80px; height: 80px; flex-shrink: 0;
animation: ringPulse 3s ease-in-out infinite;
}
.badge {
display: inline-flex; align-items: center; gap: 4px;
padding: 4px 12px; border-radius: 20px; font-size: 0.75rem; font-weight: 600; letter-spacing: 0.03em;
}
.badge-green { background: rgba(16,185,129,0.15); color: #6ee7b7; border: 1px solid rgba(16,185,129,0.3); }
.badge-yellow { background: rgba(245,158,11,0.15); color: #fde68a; border: 1px solid rgba(245,158,11,0.3); }
.badge-red { background: rgba(239,68,68,0.15); color: #fca5a5; border: 1px solid rgba(239,68,68,0.3); }
.tip-box {
background: rgba(99,102,241,0.06); border: 1px solid rgba(99,102,241,0.12);
border-radius: var(--radius-sm); padding: 1rem 1.2rem; margin-top: 1rem;
font-size: 0.88rem; color: #cbd5e1; line-height: 1.65;
}
.tip-box b { color: var(--text-primary); }
.insight-card {
background: var(--bg-card); backdrop-filter: blur(var(--glass-blur));
border: 1px solid var(--border-glass); border-radius: var(--radius-sm);
padding: 0.9rem 1.1rem; margin-bottom: 0.6rem;
display: flex; align-items: flex-start; gap: 0.7rem;
font-size: 0.9rem; line-height: 1.55; animation: fadeInUp 0.4s ease-out both;
}
.insight-icon { font-size: 1.1rem; flex-shrink: 0; margin-top: 1px; }
.insight-text { color: #cbd5e1; }
.insight-text strong { color: var(--text-primary); }
.login-card {
background: var(--bg-card); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px);
border: 1px solid var(--border-glass); border-radius: var(--radius-xl);
padding: 3rem 2.5rem; text-align: center; max-width: 500px; margin: 2rem auto;
animation: fadeInUp 0.6s ease-out both; position: relative; overflow: hidden;
}
.login-card::before {
content: ''; position: absolute; top: -1px; left: 20%; right: 20%; height: 2px;
background: linear-gradient(90deg, transparent, var(--accent-indigo), var(--accent-cyan), transparent);
}
.login-icon {
width: 72px; height: 72px;
background: linear-gradient(135deg, rgba(99,102,241,0.2), rgba(139,92,246,0.2));
border: 1px solid rgba(99,102,241,0.3); border-radius: 20px;
margin: 0 auto 1.5rem auto; display: flex; align-items: center; justify-content: center;
font-size: 2rem; animation: float 3s ease-in-out infinite;
}
.login-title { font-size: 1.4rem; font-weight: 700; color: var(--text-primary); margin-bottom: 0.6rem; }
.login-desc { color: var(--text-secondary); font-size: 0.92rem; line-height: 1.6; margin-bottom: 1.5rem; }
.trust-badges { display: flex; justify-content: center; gap: 0.6rem; flex-wrap: wrap; margin-bottom: 1.8rem; }
.trust-badge {
background: rgba(255,255,255,0.04); border: 1px solid rgba(255,255,255,0.08);
border-radius: 20px; padding: 5px 14px; font-size: 0.75rem; color: var(--text-secondary); font-weight: 500;
}
.login-btn {
display: block; background: linear-gradient(135deg, #ef4444, #dc2626);
color: white !important; border-radius: var(--radius-md); padding: 1rem 2rem;
font-size: 1.05rem; font-weight: 700; text-align: center; text-decoration: none !important;
transition: transform var(--transition-fast), box-shadow var(--transition-fast);
box-shadow: 0 4px 20px rgba(239,68,68,0.25);
}
.login-btn:hover { transform: translateY(-2px); box-shadow: 0 8px 30px rgba(239,68,68,0.35); }
.login-trust-line { margin-top: 1.2rem; font-size: 0.82rem; color: var(--success); font-weight: 500; }
[data-testid="stSidebar"] {
background: linear-gradient(180deg, #0d1220 0%, #0a0e1a 100%) !important;
border-right: 1px solid var(--border-subtle) !important;
}
[data-testid="stSidebar"] [data-testid="stMarkdownContainer"] p { font-family: 'Inter', sans-serif !important; }
.sidebar-status {
background: rgba(16,185,129,0.1); border: 1px solid rgba(16,185,129,0.25);
border-radius: var(--radius-sm); padding: 0.7rem 1rem;
display: flex; align-items: center; gap: 0.6rem;
font-size: 0.88rem; color: #6ee7b7; font-weight: 600; margin-bottom: 1rem;
}
.sidebar-status-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--success); box-shadow: 0 0 6px var(--success); }
.sidebar-step { display: flex; align-items: flex-start; gap: 0.7rem; margin-bottom: 0.8rem; }
.sidebar-step-num {
width: 24px; height: 24px; border-radius: 50%;
background: rgba(99,102,241,0.15); border: 1px solid rgba(99,102,241,0.3);
display: flex; align-items: center; justify-content: center;
font-size: 0.72rem; font-weight: 700; color: var(--accent-indigo); flex-shrink: 0; margin-top: 1px;
}
.sidebar-step-text { font-size: 0.88rem; color: var(--text-secondary); line-height: 1.4; }
.stButton > button {
font-family: 'Inter', sans-serif !important;
background: linear-gradient(135deg, var(--accent-indigo), var(--accent-purple)) !important;
color: white !important; border: none !important; border-radius: var(--radius-md) !important;
padding: 0.7rem 2rem !important; font-size: 1rem !important; font-weight: 600 !important;
letter-spacing: 0.01em;
transition: transform var(--transition-fast), box-shadow var(--transition-fast) !important;
box-shadow: 0 4px 15px rgba(99,102,241,0.25);
}
.stButton > button:hover { transform: translateY(-2px) !important; box-shadow: 0 8px 25px rgba(99,102,241,0.35) !important; }
.stTextInput > div > div > input {
font-family: 'Inter', sans-serif !important; background: var(--bg-card-solid) !important;
border: 1px solid var(--border-glass) !important; border-radius: var(--radius-sm) !important;
color: var(--text-primary) !important; padding: 0.7rem 1rem !important;
}
.stTextInput > div > div > input:focus { border-color: var(--accent-indigo) !important; box-shadow: 0 0 0 2px rgba(99,102,241,0.2) !important; }
[data-testid="stFileUploader"] { font-family: 'Inter', sans-serif !important; }
[data-testid="stFileUploader"] section {
background: var(--bg-card-solid) !important; border: 1px dashed var(--border-glass) !important;
border-radius: var(--radius-sm) !important; padding: 1rem !important;
}
.stProgress > div > div > div { background: linear-gradient(90deg, var(--accent-indigo), var(--accent-cyan)) !important; border-radius: 10px !important; }
[data-testid="stExpander"] { background: var(--bg-card) !important; border: 1px solid var(--border-glass) !important; border-radius: var(--radius-md) !important; }
[data-testid="stExpander"] summary { font-family: 'Inter', sans-serif !important; font-weight: 600 !important; }
.stDataFrame { border-radius: var(--radius-sm) !important; overflow: hidden; }
.gradient-divider { height: 1px; border: none; background: linear-gradient(90deg, transparent, var(--border-glass), transparent); margin: 2rem 0; }
.footer { text-align: center; padding: 2rem 0 1rem 0; color: var(--text-muted); font-size: 0.8rem; }
.footer-brand {
font-weight: 600;
background: linear-gradient(90deg, var(--accent-indigo), var(--accent-cyan));
-webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text;
}
/* ββ Predict Mode Badge ββ */
.predict-badge {
display: inline-flex; align-items: center; gap: 6px;
background: rgba(139,92,246,0.15); border: 1px solid rgba(139,92,246,0.3);
color: #c4b5fd; border-radius: 20px; padding: 5px 14px;
font-size: 0.8rem; font-weight: 600; margin-bottom: 1rem;
}
</style>
""", unsafe_allow_html=True)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# HELPERS
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def get_spot_quality(retention):
if retention >= 50:
return "β¦", "Great Spot", "placement-card", "badge-green"
elif retention >= 30:
return "β", "Decent Spot", "placement-card-warn", "badge-yellow"
else:
return "βΌ", "Weak Spot", "placement-card-bad", "badge-red"
def get_type_label(t):
return {
"scene_change": "π¬ Scene Break",
"silence": "π Quiet Moment",
"transcript_boundary": "π£οΈ Topic Change"
}.get(t, t)
def get_type_tip(t):
return {
"scene_change": "The video visually transitions here β viewers naturally expect a brief pause. Perfect for a sponsorship read.",
"silence": "There's a quiet gap in audio here β inserting an ad won't feel jarring or cut off speech.",
"transcript_boundary": "The speaker shifts to a new topic β a natural mental break for the viewer."
}.get(t, "Natural break detected in the video.")
def extract_video_id(url):
import re
for pattern in [r"youtu\.be/([^?&]+)", r"youtube\.com/watch\?v=([^&]+)"]:
m = re.search(pattern, url)
if m:
return m.group(1)
if re.match(r'^[A-Za-z0-9_-]{11}$', url.strip()):
return url.strip()
return None
def load_json(path):
if not os.path.exists(path):
return None
with open(path) as f:
return json.load(f)
def build_retention_ring(percent, color, size=76):
radius = 30
circumference = 2 * math.pi * radius
offset = circumference - (percent / 100) * circumference
return f"""
<svg width="{size}" height="{size}" viewBox="0 0 {size} {size}">
<circle cx="{size//2}" cy="{size//2}" r="{radius}"
fill="none" stroke="rgba(255,255,255,0.06)" stroke-width="6"/>
<circle cx="{size//2}" cy="{size//2}" r="{radius}"
fill="none" stroke="{color}" stroke-width="6"
stroke-linecap="round"
stroke-dasharray="{circumference}"
stroke-dashoffset="{offset}"
transform="rotate(-90 {size//2} {size//2})"
style="transition: stroke-dashoffset 1s ease-out;"/>
<text x="{size//2}" y="{size//2 + 1}" text-anchor="middle"
dominant-baseline="middle" fill="{color}"
font-size="14" font-weight="800"
font-family="Inter, sans-serif">{percent:.0f}%</text>
</svg>"""
def get_favicon_base64():
try:
if os.path.exists("favicon.png"):
with open("favicon.png", "rb") as f:
return base64.b64encode(f.read()).decode()
except Exception:
pass
return None
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# HERO HEADER
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
favicon_b64 = get_favicon_base64()
icon_html = f'<img src="data:image/png;base64,{favicon_b64}" style="height:1.2em; vertical-align:middle; margin-right:0.3rem;" />' if favicon_b64 else "[ βΆοΈ ]"
st.markdown(f"""
<div style="animation: fadeInUp 0.5s ease-out both;">
<div class="hero-title">{icon_html} Ad Placement Recommender</div>
<div class="hero-subtitle">
Find the perfect moments in your video to place ads β so viewers stay happy and you earn more.
</div>
<div class="hero-accent-line"></div>
</div>
""", unsafe_allow_html=True)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# AUTH GATE
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
creds = get_credentials()
if creds is None:
st.markdown('<div class="gradient-divider"></div>', unsafe_allow_html=True)
col1, col2, col3 = st.columns([1, 2, 1])
with col2:
auth_url = show_login_button()
st.markdown(f"""
<div class="login-card">
<div class="login-icon">α―β€</div>
<div class="login-title">Connect Your YouTube Account</div>
<div class="login-desc">
We need read-only access to your YouTube Analytics
to see where viewers drop off in your videos.
</div>
<div class="trust-badges">
<span class="trust-badge">π Read-Only Access</span>
<span class="trust-badge">π‘οΈ 256-bit Encrypted</span>
<span class="trust-badge">π« No Data Stored</span>
</div>
<a href="{auth_url}" target="_blank" class="login-btn">
βΆ Sign in with YouTube
</a>
<div class="login-trust-line">
β We never post, modify, or delete anything
</div>
</div>
""", unsafe_allow_html=True)
st.stop()
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# SIDEBAR
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
with st.sidebar:
st.markdown("### π€ Account")
st.markdown("""
<div class="sidebar-status">
<div class="sidebar-status-dot"></div>
YouTube Connected
</div>
""", unsafe_allow_html=True)
if st.button("πͺ Logout"):
logout()
st.rerun()
st.markdown('<div class="gradient-divider"></div>', unsafe_allow_html=True)
st.markdown("### βΉοΈ How It Works")
steps = [
("1", "α―β€ Paste YouTube URL <em>(optional for unpublished)</em>"),
("2", "π¬ Upload your video as <code>.mp4</code>"),
("3", "π Click <strong>Analyze</strong>"),
("4", "π See exactly where to place ads"),
]
for num, text in steps:
st.markdown(f"""
<div class="sidebar-step">
<div class="sidebar-step-num">{num}</div>
<div class="sidebar-step-text">{text}</div>
</div>
""", unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
st.markdown(
'<div style="text-align:center;color:var(--text-muted);font-size:0.75rem;">'
'Ad Placement Recommender<br>Built for YouTube Creators</div>',
unsafe_allow_html=True
)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# INPUT FORM
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
st.markdown('<div class="section-header">π₯ Analyze Your Video</div>', unsafe_allow_html=True)
col1, col2 = st.columns([1, 1])
with col1:
yt_input = st.text_input(
"[ βΆοΈ ] YouTube Video URL (optional for unpublished videos)",
placeholder="https://youtu.be/4Rq-LY16WxM",
help="Leave blank if video is not yet published on YouTube"
)
with col2:
uploaded_file = st.file_uploader(
"π¬ Upload Your Video File (.mp4)",
type=["mp4"],
help="Upload your video file β required for analysis"
)
analyze_btn = st.button("π Analyze My Video & Find Best Ad Spots")
if analyze_btn:
# ββ Validate: video file is always required ββ
if not uploaded_file:
st.warning("β οΈ Please upload your video file (.mp4) to continue.")
else:
# ββ Determine pipeline mode ββ
use_offline = not yt_input.strip()
video_id = extract_video_id(yt_input.strip()) if yt_input.strip() else None
if yt_input.strip() and not video_id:
st.error("β Could not extract video ID. Please check your YouTube URL.")
else:
# Save uploaded file to temp path
os.makedirs("test_video", exist_ok=True)
save_path = os.path.join("test_video", uploaded_file.name)
with open(save_path, "wb") as f:
f.write(uploaded_file.getbuffer())
# Loading UI
loading_container = st.empty()
with loading_container.container():
if use_offline:
st.markdown("""
<div class="glass-card" style="text-align:center; padding:3rem; margin:2rem 0; animation: progressPulse 2s infinite;">
<div style="font-size:2.5rem; animation: float 3s infinite ease-in-out; margin-bottom:1rem;">[ βΆοΈ ]</div>
<div style="font-size:1.3rem; font-weight:700; color:var(--text-primary); margin-bottom:0.5rem;">
Predicting Ad Spots...
</div>
<div style="color:var(--accent-cyan); font-size:0.95rem; font-weight:600;">
Analyzing audio energy to simulate viewer retention
</div>
<div class="predict-badge" style="margin-top:1rem; display:inline-flex;">
[ βΆοΈ ] Pre-Publish Prediction Mode
</div>
</div>
""", unsafe_allow_html=True)
else:
st.markdown("""
<div class="glass-card" style="text-align:center; padding:3rem; margin:2rem 0; animation: progressPulse 2s infinite;">
<div style="font-size:2.5rem; animation: float 3s infinite ease-in-out; margin-bottom:1rem;">[ βΆοΈ ]</div>
<div style="font-size:1.3rem; font-weight:700; color:var(--text-primary); margin-bottom:0.5rem;">
Analyzing Video Content...
</div>
<div style="color:var(--accent-cyan); font-size:0.95rem; font-weight:600;">
Processing frames and fetching YouTube retention data
</div>
</div>
""", unsafe_allow_html=True)
progress_bar = st.progress(0)
steps_done = [0]
def on_progress(msg):
steps_done[0] += 1
progress_bar.progress(min(steps_done[0] / 4, 1.0))
try:
if use_offline:
# ββ Unpublished video β audio-based prediction ββ
from pipeline import run_full_pipeline_offline
run_full_pipeline_offline(save_path, progress_callback=on_progress)
st.session_state["prediction_mode"] = True
else:
# ββ Published video β full YouTube Analytics pipeline ββ
from pipeline import run_full_pipeline
run_full_pipeline(save_path, video_id, creds, progress_callback=on_progress)
st.session_state["prediction_mode"] = False
progress_bar.progress(1.0)
loading_container.empty()
st.session_state["analysis_done"] = True
st.rerun()
except Exception as e:
loading_container.empty()
st.error(f"β Pipeline error: {str(e)}")
if not use_offline:
st.info("π‘ Make sure your video is public or unlisted and belongs to your connected YouTube channel.")
st.markdown('<div class="gradient-divider"></div>', unsafe_allow_html=True)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# LOAD RESULTS
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if not st.session_state.get("analysis_done", False):
data = None
else:
data = load_json("final_recommendations.json")
candidates = load_json("ranked_candidates.json") if st.session_state.get("analysis_done") else None
retention = load_json("retention_curve.json") if st.session_state.get("analysis_done") else None
if not data:
st.markdown("""
<div class="glass-card" style="text-align:center;padding:3rem;">
<div style="font-size:2.5rem;margin-bottom:0.8rem;">πΉ</div>
<div style="font-size:1.1rem;font-weight:600;color:var(--text-primary);margin-bottom:0.4rem;">
Ready to analyze your video
</div>
<div style="color:var(--text-secondary);font-size:0.92rem;">
Upload your video above β paste a YouTube URL for published videos,
or leave it blank to predict spots for an unpublished video.
</div>
</div>
""", unsafe_allow_html=True)
st.stop()
recs = data.get("recommendations", [])
duration = data.get("video_duration_formatted", "N/A")
total_placed = data.get("total_placements_recommended", 0)
cands_list = candidates.get("ranked_placements", []) if candidates else []
top_ret = max((c["retention_at_t"] for c in cands_list), default=0)
is_predict = st.session_state.get("prediction_mode", False)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# PREDICTION MODE BANNER
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if is_predict:
st.markdown("""
<div class="glass-card" style="border-left: 4px solid #8b5cf6; padding: 1rem 1.5rem; margin-bottom:1rem;">
<span class="predict-badge">[ βΆοΈ ] Pre-Publish Prediction Mode</span>
<div style="color:var(--text-secondary); font-size:0.9rem; margin-top:0.3rem;">
No YouTube data available yet β ad spots are predicted using <strong>audio energy analysis</strong>.
Accuracy improves once you publish and re-analyze with real viewer retention data.
</div>
</div>
""", unsafe_allow_html=True)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# METRICS
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
metrics_data = [
("π¬", "Video Duration", duration, "#e2e8f0", "rgba(99,102,241,0.15)"),
("π", "Ad Spots Found", str(total_placed), "#10b981" if total_placed > 0 else "#ef4444", "rgba(16,185,129,0.15)" if total_placed > 0 else "rgba(239,68,68,0.15)"),
("π¬", "Moments Analyzed", str(len(cands_list)), "#e2e8f0", "rgba(99,102,241,0.15)"),
("π", "Best Retention", f"{top_ret:.0f}%", "#10b981" if top_ret >= 50 else "#f59e0b", "rgba(16,185,129,0.15)" if top_ret >= 50 else "rgba(245,158,11,0.15)"),
]
m1, m2, m3, m4 = st.columns(4)
for i, (col, (icon, label, value, color, icon_bg)) in enumerate(zip([m1, m2, m3, m4], metrics_data)):
with col:
st.markdown(f"""
<div class="metric-card" style="animation-delay:{i*0.1}s;">
<div class="metric-icon" style="background:{icon_bg};">{icon}</div>
<div class="metric-label">{label}</div>
<div class="metric-value" style="color:{color};">{value}</div>
</div>""", unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# RETENTION CURVE
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
st.markdown('<div class="section-header">π Viewer Retention Curve</div>', unsafe_allow_html=True)
if is_predict:
st.caption("Simulated retention curve based on audio energy analysis. Markers show predicted ad spots.")
else:
st.caption("How many viewers are still watching at each moment. Markers show recommended ad spots.")
if retention:
times = [p["time_seconds"] for p in retention]
values = [p["retention_percent"] for p in retention]
fig = go.Figure()
fig.add_trace(go.Scatter(
x=times, y=values, mode="lines",
name="Viewer Retention",
line=dict(color="#6366f1", width=3, shape="spline", smoothing=1.2),
fill="tozeroy",
fillgradient=dict(
type="vertical",
colorscale=[[0.0, "rgba(99,102,241,0.0)"], [1.0, "rgba(99,102,241,0.2)"]]
),
hovertemplate="<b>%{x:.0f}s</b><br>Retention: %{y:.1f}%<extra></extra>"
))
spot_colors = ["#10b981", "#f59e0b", "#ef4444"]
for i, r in enumerate(recs):
color = spot_colors[i % len(spot_colors)]
ts = r["timestamp_seconds"]
ret_val = r.get("retention_at_t", 50)
fig.add_trace(go.Scatter(
x=[ts], y=[ret_val],
mode="markers+text",
marker=dict(symbol="diamond", size=14, color=color, line=dict(width=2, color="white")),
text=[f"Ad {r['placement_number']}"],
textposition="top center",
textfont=dict(color=color, size=12, family="Inter"),
hovertemplate=f"<b>Ad Spot {r['placement_number']}</b><br>{r['timestamp_formatted']}<br>Retention: {ret_val:.1f}%<extra></extra>",
showlegend=False
))
fig.add_vline(x=ts, line_dash="dot", line_color=color, line_width=1.5, opacity=0.5)
fig.update_layout(
plot_bgcolor="rgba(0,0,0,0)", paper_bgcolor="rgba(0,0,0,0)",
font=dict(color="#94a3b8", family="Inter"), height=400,
xaxis=dict(title="Time (seconds)", gridcolor="rgba(255,255,255,0.04)", zeroline=False, tickfont=dict(size=11)),
yaxis=dict(title="Viewers Still Watching (%)", gridcolor="rgba(255,255,255,0.04)", range=[0, 105], zeroline=False, tickfont=dict(size=11)),
margin=dict(l=10, r=10, t=20, b=40),
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1, bgcolor="rgba(0,0,0,0)"),
hoverlabel=dict(bgcolor="#161c2d", bordercolor="#6366f1", font_size=13, font_family="Inter")
)
st.plotly_chart(fig, width='stretch')
st.markdown('<div class="gradient-divider"></div>', unsafe_allow_html=True)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# RECOMMENDATIONS
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
st.markdown(
f'<div class="section-header">{"[ βΆοΈ ] Predicted" if is_predict else "π―"} Where to Place Your Ads</div>',
unsafe_allow_html=True
)
if not recs:
st.markdown("""
<div class="glass-card" style="text-align:center;">
<div style="font-size:2.2rem;margin-bottom:0.5rem;">π</div>
<div style="font-size:1.1rem;color:#f87171;font-weight:600;margin-bottom:0.4rem;">
No strong ad spots found for this video
</div>
<div style="color:var(--text-secondary);font-size:0.9rem;">
This usually means viewer retention dropped too quickly.<br>
Try a video where viewers watch past the halfway point.
</div>
</div>
""", unsafe_allow_html=True)
else:
for idx, r in enumerate(recs):
emoji, quality, card_class, badge_class = get_spot_quality(r["retention_at_t"])
type_label = get_type_label(r["type"])
type_tip = get_type_tip(r["type"])
ret = r["retention_at_t"]
conf = r["confidence"]
conf_color = "#10b981" if conf == "HIGH" else "#f59e0b" if conf == "MEDIUM" else "#94a3b8"
ring_color = "#10b981" if ret >= 50 else "#f59e0b" if ret >= 30 else "#ef4444"
ring_svg = build_retention_ring(ret, ring_color)
is_predict = st.session_state.get("prediction_mode", False)
predict_note = "<em style='color:#a78bfa;font-size:0.8rem;'>(predicted)</em>" if is_predict else ""
html = (
f'<div class="{card_class}" style="animation-delay:{idx*0.12}s;">'
f'<div class="placement-header">'
f'<div>'
f'<span class="placement-title">π Ad Spot {r["placement_number"]}</span>'
f' '
f'<span class="placement-timestamp">{r["timestamp_formatted"]}</span>'
f' {predict_note}'
f'</div>'
f'<span class="badge {badge_class}">{emoji} {quality}</span>'
f'</div>'
f'<div class="placement-body">'
f'<div class="placement-stats">'
f'<div class="stat-block">'
f'<div class="stat-label">VIEWERS WATCHING</div>'
f'<div class="stat-value" style="color:{ring_color};">{ret:.0f}%</div>'
f'</div>'
f'<div class="stat-block">'
f'<div class="stat-label">BREAK TYPE</div>'
f'<div class="stat-value-sm">{type_label}</div>'
f'</div>'
f'<div class="stat-block">'
f'<div class="stat-label">CONFIDENCE</div>'
f'<div class="stat-value-sm" style="color:{conf_color};">{conf}</div>'
f'</div>'
f'</div>'
f'<div class="retention-ring-container">{ring_svg}</div>'
f'</div>'
f'<div class="tip-box">'
f'<b>Why this spot?</b> {type_tip}<br><br>'
f'<b>What to do:</b> Place your sponsorship or enable mid-roll at <b>{r["timestamp_formatted"]}</b>. '
f'At this moment, <b>{ret:.0f}% of your audience</b> is still watching.'
f'</div>'
f'</div>'
)
st.markdown(html, unsafe_allow_html=True)
st.markdown('<div class="gradient-divider"></div>', unsafe_allow_html=True)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# INSIGHTS FOR NEXT VIDEO
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
st.markdown('<div class="section-header">π Insights for Your Next Video</div>', unsafe_allow_html=True)
if cands_list:
df = pd.DataFrame(cands_list)
best_ret = df["retention_at_t"].max()
worst_ret = df["retention_at_t"].min()
avg_ret = df["retention_at_t"].mean()
drop_time = df.loc[df["retention_at_t"].idxmin(), "timestamp_formatted"]
insight_metrics = [
("π", "Peak Retention", f"{best_ret:.0f}%", "#10b981", "rgba(16,185,129,0.15)", "viewers at best moment"),
("π", "Biggest Drop-Off", drop_time, "#ef4444", "rgba(239,68,68,0.15)", "most viewers left here"),
("π", "Avg Retention", f"{avg_ret:.0f}%", "#f59e0b", "rgba(245,158,11,0.15)", "across all break points"),
]
i1, i2, i3 = st.columns(3)
for i, (col, (icon, label, value, color, icon_bg, sub)) in enumerate(zip([i1, i2, i3], insight_metrics)):
with col:
st.markdown(f"""
<div class="metric-card" style="animation-delay:{i*0.1}s;">
<div class="metric-icon" style="background:{icon_bg};">{icon}</div>
<div class="metric-label">{label}</div>
<div class="metric-value" style="color:{color};">{value}</div>
<div style="color:var(--text-muted);font-size:0.78rem;margin-top:0.3rem;">{sub}</div>
</div>""", unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
st.markdown('<div class="section-header" style="font-size:1.1rem;">π‘ What This Means for Your Next Video</div>', unsafe_allow_html=True)
tips = []
if best_ret >= 60:
tips.append(("β
", "Strong early retention β your intro hooks viewers well. Keep doing what you did in the first 2 minutes."))
if worst_ret < 25:
tips.append(("β οΈ", f"Viewers drop off near <strong>{drop_time}</strong> β tighten that section or add a re-engagement hook."))
if avg_ret < 35:
tips.append(("π", "Overall retention is low β try shorter videos or stronger pacing."))
if avg_ret >= 50:
tips.append(("π", "Great overall retention β you can confidently place ads and expect good visibility."))
if total_placed == 0:
tips.append(("π΄", "No strong ad spots this time β aim to keep 40%+ viewers watching past the 2-minute mark."))
if is_predict:
tips.append(("[ βΆοΈ ]", "This was a <strong>predicted</strong> analysis. Once published, re-analyze with your YouTube URL for real retention data and more accurate spots."))
for icon, text in tips:
st.markdown(f"""
<div class="insight-card">
<div class="insight-icon">{icon}</div>
<div class="insight-text">{text}</div>
</div>
""", unsafe_allow_html=True)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# ADVANCED TABLE
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
st.markdown('<div class="gradient-divider"></div>', unsafe_allow_html=True)
with st.expander("π¬ View All Analyzed Moments (Advanced)"):
if cands_list:
df_show = pd.DataFrame(cands_list)[["timestamp_formatted", "type", "retention_at_t", "placement_score"]]
df_show.columns = ["Timestamp", "Break Type", "Viewers Watching (%)", "ML Score"]
df_show["Break Type"] = df_show["Break Type"].map(get_type_label)
df_show["Viewers Watching (%)"] = df_show["Viewers Watching (%)"].map(lambda x: f"{x:.1f}%")
df_show["ML Score"] = df_show["ML Score"].map(lambda x: f"{x:.4f}")
st.dataframe(df_show, width='stretch', hide_index=True)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# PAST ANALYSES (CHANNEL HISTORY)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
history_data = load_json("channel_history.json")
if history_data:
st.markdown('<div class="gradient-divider"></div>', unsafe_allow_html=True)
with st.expander("π Past Analyses (Channel History)"):
st.markdown("""
### Why It's Important
Right now, your app analyzes each video in isolation β it has no memory. Every analysis starts fresh with zero knowledge of your channel's patterns. History storage gives the system memory and intelligence over time.
**Without History (Now)**
* Video 1 analyzed β recommendations β forgotten β
* Video 2 analyzed β recommendations β forgotten β
* *Each video treated like the first video ever*
**With History (After)**
* Video 1 analyzed β saved to history β
* Video 2 analyzed β compared to Video 1 β better prediction β
* Video 10 analyzed β compared to 9 past videos β highly accurate β
* *System gets SMARTER with every video you analyze*
<br><br>
""", unsafe_allow_html=True)
# Reverse the list so newest is on top
history_data = history_data[::-1]
df_history = pd.DataFrame(history_data)
df_history = df_history[["timestamp", "video_path", "duration", "placements", "is_prediction"]]
df_history.columns = ["Date", "Video", "Duration", "Spots Found", "Predicted?"]
df_history["Predicted?"] = df_history["Predicted?"].apply(lambda x: "[ βΆοΈ ] Yes" if x else "β
No")
st.dataframe(df_history, width='stretch', hide_index=True)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# FOOTER
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
st.markdown("""
<div class="gradient-divider"></div>
<div class="footer">
<span class="footer-brand">Ad Placement Recommender</span>
Β· Built with β€οΈ for YouTube Creators
</div>
""", unsafe_allow_html=True) |